diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index f7d666d6eb..1e95efced1 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -2,8 +2,8 @@ name: Pull Request on: pull_request: - types: [opened, reopened, synchronize, ready_for_review] - + types: [opened, reopened, synchronize] + jobs: call-pull-request-soundness-workflow: name: Soundness @@ -17,6 +17,9 @@ jobs: with: name: "Unit tests" matrix_linux_command: "swift test -Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" + # Disable warnings as errors: Swift 6 emits sendability warnings that haven't been dealt with yet. + matrix_linux_nightly_main_command_override: "swift test --explicit-target-dependency-import-check error" + matrix_linux_nightly_6_0_command_override: "swift test --explicit-target-dependency-import-check error" call-pull-request-benchmark-workflow: name: Benchmarks diff --git a/Benchmarks/Benchmarks/NIOPosixBenchmarks/TCPEcho.swift b/Benchmarks/Benchmarks/NIOPosixBenchmarks/TCPEcho.swift index a1ca7a5df4..762ab260f4 100644 --- a/Benchmarks/Benchmarks/NIOPosixBenchmarks/TCPEcho.swift +++ b/Benchmarks/Benchmarks/NIOPosixBenchmarks/TCPEcho.swift @@ -46,7 +46,7 @@ private final class EchoRequestChannelHandler: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) self.receivedData += buffer.readableBytes if self.receivedData == self.numberOfWrites * self.messageSize { diff --git a/Benchmarks/Thresholds/5.10/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/5.10/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/5.10/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/5.10/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Benchmarks/Thresholds/5.8/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/5.8/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/5.8/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/5.8/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Benchmarks/Thresholds/5.9/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/5.9/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/5.9/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/5.9/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Benchmarks/Thresholds/nightly-main/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/nightly-main/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/nightly-main/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/nightly-main/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index b3d660a648..32f5d6112d 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -1,8 +1,8 @@ { - "10000000_asyncsequenceproducer": 21, + "10000000_asyncsequenceproducer": 19, "1000000_asyncwriter": 1000050, - "1000_addHandlers": 45050, - "1000_addHandlers_sync": 38050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, "1000_addRemoveHandlers_handlercontext": 8050, "1000_addRemoveHandlers_handlername": 8050, "1000_addRemoveHandlers_handlertype": 8050, @@ -11,15 +11,15 @@ "1000_copying_bytebufferview_to_array": 1050, "1000_copying_circularbuffer_to_array": 1050, "1000_getHandlers": 8050, - "1000_getHandlers_sync": 36, + "1000_getHandlers_sync": 35, "1000_reqs_1_conn": 26400, - "1000_rst_connections": 147000, + "1000_rst_connections": 145050, "1000_tcpbootstraps": 3050, - "1000_tcpconnections": 155050, + "1000_tcpconnections": 152050, "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, - "1000_udpconnections": 76050, - "1_reqs_1000_conn": 393000, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 389050, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -42,10 +42,9 @@ "modifying_byte_buffer_view": 6050, "ping_pong_1000_reqs_1_conn": 343, "read_10000_chunks_from_file": 110200, - "schedule_10000_tasks": 50100, + "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, "scheduling_10000_executions": 89, "udp_1000_reqs_1_conn": 6200, - "udp_1_reqs_1000_conn": 165050 - } - \ No newline at end of file + "udp_1_reqs_1000_conn": 162050 +} diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 5792388db3..32f5d6112d 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -1,50 +1,50 @@ { - "10000000_asyncsequenceproducer": 21, - "1000000_asyncwriter": 1000050, - "1000_addHandlers": 45050, - "1000_addHandlers_sync": 38050, - "1000_addRemoveHandlers_handlercontext": 8050, - "1000_addRemoveHandlers_handlername": 8050, - "1000_addRemoveHandlers_handlertype": 8050, - "1000_autoReadGetAndSet": 18050, - "1000_autoReadGetAndSet_sync": 0, - "1000_copying_bytebufferview_to_array": 1050, - "1000_copying_circularbuffer_to_array": 1050, - "1000_getHandlers": 8050, - "1000_getHandlers_sync": 36, - "1000_reqs_1_conn": 26400, - "1000_rst_connections": 147000, - "1000_tcpbootstraps": 3050, - "1000_tcpconnections": 155050, - "1000_udp_reqs": 6050, - "1000_udpbootstraps": 2050, - "1000_udpconnections": 76050, - "1_reqs_1000_conn": 393000, - "bytebuffer_lots_of_rw": 2050, - "creating_10000_headers": 0, - "decode_1000_ws_frames": 2050, - "encode_1000_ws_frames_holding_buffer": 3, - "encode_1000_ws_frames_holding_buffer_with_mask": 2050, - "encode_1000_ws_frames_holding_buffer_with_space": 3, - "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, - "encode_1000_ws_frames_new_buffer": 3050, - "encode_1000_ws_frames_new_buffer_with_mask": 5050, - "encode_1000_ws_frames_new_buffer_with_space": 3050, - "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, - "execute_hop_10000_tasks": 0, - "future_erase_result": 4050, - "future_lots_of_callbacks": 53050, - "get_100000_headers_canonical_form": 700050, - "get_100000_headers_canonical_form_trimming_whitespace": 700050, - "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, - "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, - "modifying_1000_circular_buffer_elements": 0, - "modifying_byte_buffer_view": 6050, - "ping_pong_1000_reqs_1_conn": 343, - "read_10000_chunks_from_file": 110200, - "schedule_10000_tasks": 50100, - "schedule_and_run_10000_tasks": 50050, - "scheduling_10000_executions": 89, - "udp_1000_reqs_1_conn": 6200, - "udp_1_reqs_1000_conn": 165050 + "10000000_asyncsequenceproducer": 19, + "1000000_asyncwriter": 1000050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, + "1000_addRemoveHandlers_handlercontext": 8050, + "1000_addRemoveHandlers_handlername": 8050, + "1000_addRemoveHandlers_handlertype": 8050, + "1000_autoReadGetAndSet": 18050, + "1000_autoReadGetAndSet_sync": 0, + "1000_copying_bytebufferview_to_array": 1050, + "1000_copying_circularbuffer_to_array": 1050, + "1000_getHandlers": 8050, + "1000_getHandlers_sync": 35, + "1000_reqs_1_conn": 26400, + "1000_rst_connections": 145050, + "1000_tcpbootstraps": 3050, + "1000_tcpconnections": 152050, + "1000_udp_reqs": 6050, + "1000_udpbootstraps": 2050, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 389050, + "bytebuffer_lots_of_rw": 2050, + "creating_10000_headers": 0, + "decode_1000_ws_frames": 2050, + "encode_1000_ws_frames_holding_buffer": 3, + "encode_1000_ws_frames_holding_buffer_with_mask": 2050, + "encode_1000_ws_frames_holding_buffer_with_space": 3, + "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, + "encode_1000_ws_frames_new_buffer": 3050, + "encode_1000_ws_frames_new_buffer_with_mask": 5050, + "encode_1000_ws_frames_new_buffer_with_space": 3050, + "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, + "execute_hop_10000_tasks": 0, + "future_erase_result": 4050, + "future_lots_of_callbacks": 53050, + "get_100000_headers_canonical_form": 700050, + "get_100000_headers_canonical_form_trimming_whitespace": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, + "modifying_1000_circular_buffer_elements": 0, + "modifying_byte_buffer_view": 6050, + "ping_pong_1000_reqs_1_conn": 343, + "read_10000_chunks_from_file": 110200, + "schedule_10000_tasks": 40100, + "schedule_and_run_10000_tasks": 50050, + "scheduling_10000_executions": 89, + "udp_1000_reqs_1_conn": 6200, + "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_1000_tcpconnections.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_1000_tcpconnections.swift index df3430de44..daf87742b3 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_1000_tcpconnections.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_1000_tcpconnections.swift @@ -20,7 +20,7 @@ private final class ReceiveAndCloseHandler: ChannelInboundHandler { public typealias OutboundOut = ByteBuffer func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let byteBuffer = self.unwrapInboundIn(data) + let byteBuffer = Self.unwrapInboundIn(data) precondition(byteBuffer.readableBytes == 1) context.channel.close(promise: nil) } diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_1000_udp_reqs.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_1000_udp_reqs.swift index 8ad878f1ee..f87d529add 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_1000_udp_reqs.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_1000_udp_reqs.swift @@ -73,7 +73,7 @@ private final class ClientHandler: ChannelInboundHandler { // Send the data with ECN let metadata = AddressedEnvelope.Metadata(ecnState: .transportCapableFlag1) let envelope = AddressedEnvelope(remoteAddress: remoteAddress, data: buffer, metadata: metadata) - clientChannel.writeAndFlush(self.wrapOutboundOut(envelope), promise: nil) + clientChannel.writeAndFlush(Self.wrapOutboundOut(envelope), promise: nil) } func sendBytesAndWaitForReply(clientChannel: Channel) -> Int { diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift index 79edb32350..b9ee98c997 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift @@ -21,8 +21,8 @@ class UnboxingChannelHandler: ChannelInboundHandler { typealias InboundOut = WebSocketFrame func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let data = self.unwrapInboundIn(data) - context.fireChannelRead(self.wrapInboundOut(data)) + let data = Self.unwrapInboundIn(data) + context.fireChannelRead(Self.wrapInboundOut(data)) } } diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_ping_pong_1000_reqs_1_conn.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_ping_pong_1000_reqs_1_conn.swift index 8e759e44fe..ebcad8f0b5 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_ping_pong_1000_reqs_1_conn.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_ping_pong_1000_reqs_1_conn.swift @@ -28,7 +28,7 @@ private final class PongDecoder: ByteToMessageDecoder { public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { if let ping = buffer.readInteger(as: UInt8.self) { - context.fireChannelRead(self.wrapInboundOut(ping)) + context.fireChannelRead(Self.wrapInboundOut(ping)) return .continue } else { return .needMoreData @@ -69,7 +69,7 @@ private final class PingHandler: ChannelInboundHandler { self.pingBuffer = context.channel.allocator.buffer(capacity: 1) self.pingBuffer.writeInteger(PingHandler.pingCode) - context.writeAndFlush(self.wrapOutboundOut(self.pingBuffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(self.pingBuffer), promise: nil) } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { @@ -77,7 +77,7 @@ private final class PingHandler: ChannelInboundHandler { if buf.readableBytes == 1 && buf.readInteger(as: UInt8.self) == PongHandler.pongCode { if self.remainingNumberOfRequests > 0 { self.remainingNumberOfRequests -= 1 - context.writeAndFlush(self.wrapOutboundOut(self.pingBuffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(self.pingBuffer), promise: nil) } else { context.close(promise: self.allDone) } @@ -105,7 +105,7 @@ private final class PongHandler: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let data = self.unwrapInboundIn(data) + let data = Self.unwrapInboundIn(data) if data == PingHandler.pingCode { context.writeAndFlush(NIOAny(self.pongBuffer), promise: nil) } else { diff --git a/Sources/NIOAsyncAwaitDemo/FullRequestResponse.swift b/Sources/NIOAsyncAwaitDemo/FullRequestResponse.swift index 10d7a9e017..f0d03ac61d 100644 --- a/Sources/NIOAsyncAwaitDemo/FullRequestResponse.swift +++ b/Sources/NIOAsyncAwaitDemo/FullRequestResponse.swift @@ -22,10 +22,10 @@ public final class MakeFullRequestHandler: ChannelOutboundHandler { public typealias OutboundIn = HTTPRequestHead public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let req = self.unwrapOutboundIn(data) + let req = Self.unwrapOutboundIn(data) - context.write(self.wrapOutboundOut(.head(req)), promise: nil) - context.write(self.wrapOutboundOut(.end(nil)), promise: promise) + context.write(Self.wrapOutboundOut(.head(req)), promise: nil) + context.write(Self.wrapOutboundOut(.end(nil)), promise: promise) } } @@ -96,7 +96,7 @@ public final class RequestResponseHandler: ChannelDuplexHandl return } - let response = self.unwrapInboundIn(data) + let response = Self.unwrapInboundIn(data) let promise = self.promiseBuffer.removeFirst() promise.succeed(response) @@ -117,7 +117,7 @@ public final class RequestResponseHandler: ChannelDuplexHandl } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let (request, responsePromise) = self.unwrapOutboundIn(data) + let (request, responsePromise) = Self.unwrapOutboundIn(data) switch self.state { case .error(let error): assert(self.promiseBuffer.count == 0) @@ -125,7 +125,7 @@ public final class RequestResponseHandler: ChannelDuplexHandl promise?.fail(error) case .operational: self.promiseBuffer.append(responsePromise) - context.write(self.wrapOutboundOut(request), promise: promise) + context.write(Self.wrapOutboundOut(request), promise: promise) } } } diff --git a/Sources/NIOChatClient/main.swift b/Sources/NIOChatClient/main.swift index 044f119161..399d671088 100644 --- a/Sources/NIOChatClient/main.swift +++ b/Sources/NIOChatClient/main.swift @@ -27,7 +27,7 @@ private final class ChatHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) while let byte: UInt8 = buffer.readInteger() { printByte(byte) } diff --git a/Sources/NIOChatServer/main.swift b/Sources/NIOChatServer/main.swift index aa8cd6afda..df9f6e9655 100644 --- a/Sources/NIOChatServer/main.swift +++ b/Sources/NIOChatServer/main.swift @@ -28,7 +28,7 @@ final class LineDelimiterCodec: ByteToMessageDecoder { public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { let readable = buffer.withUnsafeReadableBytes { $0.firstIndex(of: newLine) } if let r = readable { - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: r + 1)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: r + 1)!)) return .continue } return .needMoreData @@ -69,7 +69,7 @@ final class ChatHandler: ChannelInboundHandler { var buffer = channel.allocator.buffer(capacity: 64) buffer.writeString("(ChatServer) - Welcome to: \(context.localAddress!)\n") - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } public func channelInactive(context: ChannelHandlerContext) { @@ -88,7 +88,7 @@ final class ChatHandler: ChannelInboundHandler { public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let id = ObjectIdentifier(context.channel) - var read = self.unwrapInboundIn(data) + var read = Self.unwrapInboundIn(data) // 64 should be good enough for the ipaddress var buffer = context.channel.allocator.buffer(capacity: read.readableBytes + 64) diff --git a/Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift b/Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift index 83e958e63e..dc5916b6dd 100644 --- a/Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift +++ b/Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift @@ -37,6 +37,46 @@ public struct NIOLockedValueBox { public func withLockedValue(_ mutate: (inout Value) throws -> T) rethrows -> T { try self._storage.withLockedValue(mutate) } + + /// Provides an unsafe view over the lock and its value. + /// + /// This can be beneficial when you require fine grained control over the lock in some + /// situations but don't want lose the benefits of ``withLockedValue(_:)`` in others by + /// switching to ``NIOLock``. + public var unsafe: Unsafe { + Unsafe(_storage: self._storage) + } + + /// Provides an unsafe view over the lock and its value. + public struct Unsafe { + @usableFromInline + let _storage: LockStorage + + /// Manually acquire the lock. + @inlinable + public func lock() { + self._storage.lock() + } + + /// Manually release the lock. + @inlinable + public func unlock() { + self._storage.unlock() + } + + /// Mutate the value, assuming the lock has been acquired manually. + /// + /// - Parameter mutate: A closure with scoped access to the value. + /// - Returns: The result of the `mutate` closure. + @inlinable + public func withValueAssumingLockIsAcquired( + _ mutate: (_ value: inout Value) throws -> Result + ) rethrows -> Result { + try self._storage.withUnsafeMutablePointerToHeader { value in + try mutate(&value.pointee) + } + } + } } extension NIOLockedValueBox: Sendable where Value: Sendable {} diff --git a/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift b/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift index ea9b7aed88..63d243b74e 100644 --- a/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift +++ b/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift @@ -175,7 +175,7 @@ extension NIOAsyncChannelHandler: ChannelInboundHandler { @inlinable func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let unwrapped = self.unwrapInboundIn(data) + let unwrapped = Self.unwrapInboundIn(data) switch self.transformation { case .syncWrapping(let transformation): @@ -477,7 +477,7 @@ extension NIOAsyncChannelHandler { @inlinable func _doOutboundWrites(context: ChannelHandlerContext, writes: Deque) { for write in writes { - context.write(self.wrapOutboundOut(write), promise: nil) + context.write(Self.wrapOutboundOut(write), promise: nil) } context.flush() @@ -485,7 +485,7 @@ extension NIOAsyncChannelHandler { @inlinable func _doOutboundWrite(context: ChannelHandlerContext, write: OutboundOut) { - context.write(self.wrapOutboundOut(write), promise: nil) + context.write(Self.wrapOutboundOut(write), promise: nil) context.flush() } } diff --git a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift index f846312a6e..64b74b1818 100644 --- a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift +++ b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift @@ -419,12 +419,12 @@ extension NIOAsyncWriter { extension NIOAsyncWriter { /// This is the underlying storage of the writer. The goal of this is to synchronize the access to all state. @usableFromInline - internal final class Storage: @unchecked Sendable { + internal struct Storage: Sendable { /// Internal type to generate unique yield IDs. /// /// This type has reference semantics. @usableFromInline - struct YieldIDGenerator { + struct YieldIDGenerator: Sendable { /// A struct representing a unique yield ID. @usableFromInline struct YieldID: Equatable, Sendable { @@ -450,27 +450,43 @@ extension NIOAsyncWriter { } } - /// The lock that protects our state. - @usableFromInline - internal let _lock = NIOLock() /// The counter used to assign an ID to all our yields. @usableFromInline internal let _yieldIDGenerator = YieldIDGenerator() /// The state machine. @usableFromInline - internal var _stateMachine: StateMachine + internal let _state: NIOLockedValueBox + + @usableFromInline + struct State: Sendable { + @usableFromInline + var stateMachine: StateMachine + @usableFromInline + var didSuspend: (@Sendable () -> Void)? + + @inlinable + init(stateMachine: StateMachine) { + self.stateMachine = stateMachine + self.didSuspend = nil + } + } + /// Hook used in testing. @usableFromInline - internal var _didSuspend: (() -> Void)? + internal func _setDidSuspend(_ didSuspend: (@Sendable () -> Void)?) { + self._state.withLockedValue { + $0.didSuspend = didSuspend + } + } @inlinable internal var isWriterFinished: Bool { - self._lock.withLock { self._stateMachine.isWriterFinished } + self._state.withLockedValue { $0.stateMachine.isWriterFinished } } @inlinable internal var isSinkFinished: Bool { - self._lock.withLock { self._stateMachine.isSinkFinished } + self._state.withLockedValue { $0.stateMachine.isSinkFinished } } @inlinable @@ -478,10 +494,8 @@ extension NIOAsyncWriter { isWritable: Bool, delegate: Delegate ) { - self._stateMachine = .init( - isWritable: isWritable, - delegate: delegate - ) + let state = State(stateMachine: StateMachine(isWritable: isWritable, delegate: delegate)) + self._state = NIOLockedValueBox(state) } @inlinable @@ -489,8 +503,8 @@ extension NIOAsyncWriter { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.setWritability(to: writability) + let action = self._state.withLockedValue { + $0.stateMachine.setWritability(to: writability) } switch action { @@ -527,40 +541,43 @@ extension NIOAsyncWriter { return try await withTaskCancellationHandler { // We are manually locking here to hold the lock across the withCheckedContinuation call - self._lock.lock() + let unsafe = self._state.unsafe + unsafe.lock() - let action = self._stateMachine.yield(yieldID: yieldID) + let action = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.yield(yieldID: yieldID) + } switch action { case .callDidYield(let delegate): // We are allocating a new Deque for every write here - self._lock.unlock() + unsafe.unlock() delegate.didYield(contentsOf: Deque(sequence)) self.unbufferQueuedEvents() return .yielded case .throwError(let error): - self._lock.unlock() + unsafe.unlock() throw error case .suspendTask: return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - self._stateMachine.yield( - continuation: continuation, - yieldID: yieldID - ) + let didSuspend = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.yield(continuation: continuation, yieldID: yieldID) + return $0.didSuspend + } - self._lock.unlock() - self._didSuspend?() + unsafe.unlock() + didSuspend?() } } } onCancel: { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.cancel(yieldID: yieldID) + let action = self._state.withLockedValue { + $0.stateMachine.cancel(yieldID: yieldID) } switch action { @@ -595,40 +612,42 @@ extension NIOAsyncWriter { return try await withTaskCancellationHandler { // We are manually locking here to hold the lock across the withCheckedContinuation call - self._lock.lock() + let unsafe = self._state.unsafe + unsafe.lock() - let action = self._stateMachine.yield(yieldID: yieldID) + let action = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.yield(yieldID: yieldID) + } switch action { case .callDidYield(let delegate): // We are allocating a new Deque for every write here - self._lock.unlock() + unsafe.unlock() delegate.didYield(element) self.unbufferQueuedEvents() return .yielded case .throwError(let error): - self._lock.unlock() + unsafe.unlock() throw error case .suspendTask: return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - self._stateMachine.yield( - continuation: continuation, - yieldID: yieldID - ) - - self._lock.unlock() - self._didSuspend?() + let didSuspend = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.yield(continuation: continuation, yieldID: yieldID) + return $0.didSuspend + } + unsafe.unlock() + didSuspend?() } } } onCancel: { // We must not resume the continuation while holding the lock - // because it can deadlock in combination with the underlying ulock + // because it can deadlock in combination with the underlying lock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.cancel(yieldID: yieldID) + let action = self._state.withLockedValue { + $0.stateMachine.cancel(yieldID: yieldID) } switch action { @@ -646,8 +665,8 @@ extension NIOAsyncWriter { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.writerFinish(error: error) + let action = self._state.withLockedValue { + $0.stateMachine.writerFinish(error: error) } switch action { @@ -669,8 +688,8 @@ extension NIOAsyncWriter { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.sinkFinish(error: error) + let action = self._state.withLockedValue { + $0.stateMachine.sinkFinish(error: error) } switch action { @@ -686,7 +705,7 @@ extension NIOAsyncWriter { @inlinable internal func unbufferQueuedEvents() { - while let action = self._lock.withLock({ self._stateMachine.unbufferQueuedEvents() }) { + while let action = self._state.withLockedValue({ $0.stateMachine.unbufferQueuedEvents() }) { switch action { case .callDidTerminate(let delegate, let error): delegate.didTerminate(error: error) @@ -705,12 +724,12 @@ extension NIOAsyncWriter { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension NIOAsyncWriter { @usableFromInline - internal struct StateMachine { + internal struct StateMachine: Sendable { @usableFromInline typealias YieldID = Storage.YieldIDGenerator.YieldID /// This is a small helper struct to encapsulate the two different values for a suspended yield. @usableFromInline - internal struct SuspendedYield { + internal struct SuspendedYield: Sendable { /// The yield's ID. @usableFromInline var yieldID: YieldID @@ -736,7 +755,7 @@ extension NIOAsyncWriter { /// The current state of our ``NIOAsyncWriter``. @usableFromInline - internal enum State: CustomStringConvertible { + internal enum State: Sendable, CustomStringConvertible { /// The initial state before either a call to ``NIOAsyncWriter/yield(contentsOf:)`` or /// ``NIOAsyncWriter/finish(completion:)`` happened. case initial( diff --git a/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift b/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift index d5327662cf..7b95ee86f2 100644 --- a/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift +++ b/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift @@ -397,23 +397,41 @@ extension NIOThrowingAsyncSequenceProducer { extension NIOThrowingAsyncSequenceProducer { /// This is the underlying storage of the sequence. The goal of this is to synchronize the access to all state. @usableFromInline - internal final class Storage: @unchecked Sendable { - /// The lock that protects our state. + internal struct Storage: Sendable { @usableFromInline - internal let _lock = NIOLock() - /// The state machine. - @usableFromInline - internal var _stateMachine: StateMachine - /// The delegate. + struct State: Sendable { + @usableFromInline + var stateMachine: StateMachine + @usableFromInline + var delegate: Delegate? + @usableFromInline + var didSuspend: (@Sendable () -> Void)? + + @inlinable + init( + stateMachine: StateMachine, + delegate: Delegate? = nil, + didSuspend: (@Sendable () -> Void)? = nil + ) { + self.stateMachine = stateMachine + self.delegate = delegate + self.didSuspend = didSuspend + } + } + @usableFromInline - internal var _delegate: Delegate? - /// Hook used in testing. + internal let _state: NIOLockedValueBox + @usableFromInline - internal var _didSuspend: (() -> Void)? + internal func _setDidSuspend(_ didSuspend: (@Sendable () -> Void)?) { + self._state.withLockedValue { + $0.didSuspend = didSuspend + } + } @inlinable var isFinished: Bool { - self._lock.withLock { self._stateMachine.isFinished } + self._state.withLockedValue { $0.stateMachine.isFinished } } @usableFromInline @@ -421,19 +439,22 @@ extension NIOThrowingAsyncSequenceProducer { backPressureStrategy: Strategy, delegate: Delegate ) { - self._stateMachine = .init(backPressureStrategy: backPressureStrategy) - self._delegate = delegate + let state = State( + stateMachine: .init(backPressureStrategy: backPressureStrategy), + delegate: delegate + ) + self._state = NIOLockedValueBox(state) } @inlinable internal func sequenceDeinitialized() { - let delegate: Delegate? = self._lock.withLock { - let action = self._stateMachine.sequenceDeinitialized() + let delegate: Delegate? = self._state.withLockedValue { + let action = $0.stateMachine.sequenceDeinitialized() switch action { case .callDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return delegate case .none: @@ -446,20 +467,20 @@ extension NIOThrowingAsyncSequenceProducer { @inlinable internal func iteratorInitialized() { - self._lock.withLock { - self._stateMachine.iteratorInitialized() + self._state.withLockedValue { + $0.stateMachine.iteratorInitialized() } } @inlinable internal func iteratorDeinitialized() { - let delegate: Delegate? = self._lock.withLock { - let action = self._stateMachine.iteratorDeinitialized() + let delegate: Delegate? = self._state.withLockedValue { + let action = $0.stateMachine.iteratorDeinitialized() switch action { case .callDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return delegate @@ -477,8 +498,8 @@ extension NIOThrowingAsyncSequenceProducer { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.yield(sequence) + let action = self._state.withLockedValue { + $0.stateMachine.yield(sequence) } switch action { @@ -508,14 +529,14 @@ extension NIOThrowingAsyncSequenceProducer { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let (delegate, action): (Delegate?, NIOThrowingAsyncSequenceProducer.StateMachine.FinishAction) = self._lock - .withLock { - let action = self._stateMachine.finish(failure) + let (delegate, action): (Delegate?, NIOThrowingAsyncSequenceProducer.StateMachine.FinishAction) = self + ._state.withLockedValue { + let action = $0.stateMachine.finish(failure) switch action { case .resumeContinuationWithFailureAndCallDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return (delegate, action) case .none: @@ -541,28 +562,36 @@ extension NIOThrowingAsyncSequenceProducer { @inlinable internal func next() async throws -> Element? { - try await withTaskCancellationHandler { - self._lock.lock() + try await withTaskCancellationHandler { () async throws -> Element? in + let unsafe = self._state.unsafe + unsafe.lock() - let action = self._stateMachine.next() + let action = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.next() + } switch action { case .returnElement(let element): - self._lock.unlock() + unsafe.unlock() return element case .returnElementAndCallProduceMore(let element): - let delegate = self._delegate - self._lock.unlock() + let delegate = unsafe.withValueAssumingLockIsAcquired { + $0.delegate + } + unsafe.unlock() delegate?.produceMore() return element case .returnFailureAndCallDidTerminate(let failure): - let delegate = self._delegate - self._delegate = nil - self._lock.unlock() + let delegate = unsafe.withValueAssumingLockIsAcquired { + let delegate = $0.delegate + $0.delegate = nil + return delegate + } + unsafe.unlock() delegate?.didTerminate() @@ -575,7 +604,7 @@ extension NIOThrowingAsyncSequenceProducer { } case .returnCancellationError: - self._lock.unlock() + unsafe.unlock() // We have deprecated the generic Failure type in the public API and Failure should // now be `Swift.Error`. However, if users have not migrated to the new API they could // still use a custom generic Error type and this cast might fail. @@ -590,26 +619,37 @@ extension NIOThrowingAsyncSequenceProducer { return nil case .returnNil: - self._lock.unlock() + unsafe.unlock() return nil case .suspendTask: // It is safe to hold the lock across this method // since the closure is guaranteed to be run straight away - return try await withCheckedThrowingContinuation { continuation in - let action = self._stateMachine.next(for: continuation) + return try await withCheckedThrowingContinuation { + (continuation: CheckedContinuation) in + let (action, callDidSuspend) = unsafe.withValueAssumingLockIsAcquired { + let action = $0.stateMachine.next(for: continuation) + let callDidSuspend = $0.didSuspend != nil + return (action, callDidSuspend) + } switch action { case .callProduceMore: - let delegate = _delegate - self._lock.unlock() + let delegate = unsafe.withValueAssumingLockIsAcquired { + $0.delegate + } + unsafe.unlock() delegate?.produceMore() case .none: - self._lock.unlock() + unsafe.unlock() + } + + if callDidSuspend { + let didSuspend = self._state.withLockedValue { $0.didSuspend } + didSuspend?() } - self._didSuspend?() } } } onCancel: { @@ -617,19 +657,19 @@ extension NIOThrowingAsyncSequenceProducer { // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler let (delegate, action): (Delegate?, NIOThrowingAsyncSequenceProducer.StateMachine.CancelledAction) = - self._lock.withLock { - let action = self._stateMachine.cancelled() + self._state.withLockedValue { + let action = $0.stateMachine.cancelled() switch action { case .callDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return (delegate, action) case .resumeContinuationWithCancellationErrorAndCallDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return (delegate, action) @@ -670,9 +710,9 @@ extension NIOThrowingAsyncSequenceProducer { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension NIOThrowingAsyncSequenceProducer { @usableFromInline - internal struct StateMachine { + internal struct StateMachine: Sendable { @usableFromInline - internal enum State { + internal enum State: Sendable { /// The initial state before either a call to `yield()` or a call to `next()` happened case initial( backPressureStrategy: Strategy, diff --git a/Sources/NIOCore/Codec.swift b/Sources/NIOCore/Codec.swift index 81ca4c9609..7271205df7 100644 --- a/Sources/NIOCore/Codec.swift +++ b/Sources/NIOCore/Codec.swift @@ -237,10 +237,16 @@ extension ByteToMessageDecoder { return buffer.storageCapacity > 1024 && (buffer.storageCapacity - buffer.readerIndex) < buffer.readerIndex } + @inlinable public func wrapInboundOut(_ value: InboundOut) -> NIOAny { NIOAny(value) } + @inlinable + public static func wrapInboundOut(_ value: InboundOut) -> NIOAny { + NIOAny(value) + } + public mutating func decodeLast( context: ChannelHandlerContext, buffer: inout ByteBuffer, @@ -511,7 +517,7 @@ extension ByteToMessageHandler: CanDequeueWrites where Decoder: WriteObservingBy fileprivate func dequeueWrites() { while self.queuedWrites.count > 0 { // self.decoder can't be `nil`, this is only allowed to be called when we're not already on the stack - self.decoder!.write(data: self.unwrapOutboundIn(self.queuedWrites.removeFirst())) + self.decoder!.write(data: Self.unwrapOutboundIn(self.queuedWrites.removeFirst())) } } } @@ -652,7 +658,7 @@ extension ByteToMessageHandler: ChannelInboundHandler { /// Calls `decode` until there is nothing left to decode. public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) if case .error(let error) = self.state { context.fireErrorCaught(ByteToMessageDecoderError.dataReceivedInErrorState(error, buffer)) return @@ -710,7 +716,7 @@ where Decoder: WriteObservingByteToMessageDecoder { public typealias OutboundIn = Decoder.OutboundIn public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { if self.decoder != nil { - let data = self.unwrapOutboundIn(data) + let data = Self.unwrapOutboundIn(data) assert(self.queuedWrites.isEmpty) self.decoder!.write(data: data) } else { @@ -821,12 +827,12 @@ extension MessageToByteHandler { // there's actually some work to do here break } - let data = self.unwrapOutboundIn(data) + let data = Self.unwrapOutboundIn(data) do { self.buffer!.clear() try self.encoder.encode(data: data, out: &self.buffer!) - context.write(self.wrapOutboundOut(self.buffer!), promise: promise) + context.write(Self.wrapOutboundOut(self.buffer!), promise: promise) } catch { self.state = .error(error) promise?.fail(error) diff --git a/Sources/NIOCore/NIOAny.swift b/Sources/NIOCore/NIOAny.swift index b68fe56857..1f687b134b 100644 --- a/Sources/NIOCore/NIOAny.swift +++ b/Sources/NIOCore/NIOAny.swift @@ -37,9 +37,9 @@ /// dynamically at run-time. Yet, we assert that in any configuration the channel handler before /// `SandwichHandler` does actually send us a stream of `Bacon`. /// */ -/// let bacon = self.unwrapInboundIn(data) /* `Bacon` or crash */ +/// let bacon = Self.unwrapInboundIn(data) /* `Bacon` or crash */ /// let sandwich = makeSandwich(bacon) -/// context.fireChannelRead(self.wrapInboundOut(sandwich)) /* as promised we deliver a wrapped `Sandwich` */ +/// context.fireChannelRead(Self.wrapInboundOut(sandwich)) /* as promised we deliver a wrapped `Sandwich` */ /// } /// } public struct NIOAny { @@ -48,7 +48,7 @@ public struct NIOAny { /// Wrap a value in a `NIOAny`. In most cases you should not create a `NIOAny` directly using this constructor. /// The abstraction that accepts values of type `NIOAny` must also provide a mechanism to do the wrapping. An - /// example is a `ChannelInboundHandler` which provides `self.wrapInboundOut(aValueOfTypeInboundOut)`. + /// example is a `ChannelInboundHandler` which provides `Self.wrapInboundOut(aValueOfTypeInboundOut)`. @inlinable public init(_ value: T) { self._storage = _NIOAny(value) diff --git a/Sources/NIOCore/SingleStepByteToMessageDecoder.swift b/Sources/NIOCore/SingleStepByteToMessageDecoder.swift index eca36b160f..1fed8965ac 100644 --- a/Sources/NIOCore/SingleStepByteToMessageDecoder.swift +++ b/Sources/NIOCore/SingleStepByteToMessageDecoder.swift @@ -54,7 +54,7 @@ public protocol NIOSingleStepByteToMessageDecoder: ByteToMessageDecoder { extension NIOSingleStepByteToMessageDecoder { public mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let message = try self.decode(buffer: &buffer) { - context.fireChannelRead(self.wrapInboundOut(message)) + context.fireChannelRead(Self.wrapInboundOut(message)) return .continue } else { return .needMoreData @@ -67,7 +67,7 @@ extension NIOSingleStepByteToMessageDecoder { seenEOF: Bool ) throws -> DecodingState { if let message = try self.decodeLast(buffer: &buffer, seenEOF: seenEOF) { - context.fireChannelRead(self.wrapInboundOut(message)) + context.fireChannelRead(Self.wrapInboundOut(message)) return .continue } else { return .needMoreData @@ -111,12 +111,12 @@ extension NIOSingleStepByteToMessageDecoder { /// private var messageProcessor: NIOSingleStepByteToMessageProcessor? = nil /// /// func channelRead(context: ChannelHandlerContext, data: NIOAny) { -/// let req = self.unwrapInboundIn(data) +/// let req = Self.unwrapInboundIn(data) /// do { /// switch req { /// case .head(let head): /// // simply forward on the head -/// context.fireChannelRead(self.wrapInboundOut(.head(head))) +/// context.fireChannelRead(Self.wrapInboundOut(.head(head))) /// case .body(let body): /// if self.messageProcessor == nil { /// self.messageProcessor = NIOSingleStepByteToMessageProcessor(TwoByteStringCodec()) @@ -129,7 +129,7 @@ extension NIOSingleStepByteToMessageDecoder { /// try self.messageProcessor?.finishProcessing(seenEOF: false) { message in /// self.channelReadMessage(context: context, message: message) /// } -/// context.fireChannelRead(self.wrapInboundOut(.end(trailers))) +/// context.fireChannelRead(Self.wrapInboundOut(.end(trailers))) /// } /// } catch { /// context.fireErrorCaught(error) @@ -138,7 +138,7 @@ extension NIOSingleStepByteToMessageDecoder { /// /// // Forward on the body messages as whole messages /// func channelReadMessage(context: ChannelHandlerContext, message: String) { -/// context.fireChannelRead(self.wrapInboundOut(.body(message))) +/// context.fireChannelRead(Self.wrapInboundOut(.body(message))) /// } /// } /// @@ -149,7 +149,7 @@ extension NIOSingleStepByteToMessageDecoder { /// var msgs: [String] = [] /// /// func channelRead(context: ChannelHandlerContext, data: NIOAny) { -/// let message = self.unwrapInboundIn(data) +/// let message = Self.unwrapInboundIn(data) /// /// switch message { /// case .head(let head): @@ -166,13 +166,13 @@ extension NIOSingleStepByteToMessageDecoder { /// var headers = HTTPHeaders() /// headers.add(name: "content-length", value: String(responseBuffer.readableBytes)) /// -/// context.write(self.wrapOutboundOut(HTTPServerResponsePart.head( +/// context.write(Self.wrapOutboundOut(HTTPServerResponsePart.head( /// HTTPResponseHead(version: .http1_1, /// status: .ok, headers: headers))), promise: nil) /// -/// context.write(self.wrapOutboundOut(HTTPServerResponsePart.body( +/// context.write(Self.wrapOutboundOut(HTTPServerResponsePart.body( /// .byteBuffer(responseBuffer))), promise: nil) -/// context.writeAndFlush(self.wrapOutboundOut(HTTPServerResponsePart.end(nil)), promise: nil) +/// context.writeAndFlush(Self.wrapOutboundOut(HTTPServerResponsePart.end(nil)), promise: nil) /// } /// } /// } diff --git a/Sources/NIOCore/TypeAssistedChannelHandler.swift b/Sources/NIOCore/TypeAssistedChannelHandler.swift index d121a6c647..15dd42c442 100644 --- a/Sources/NIOCore/TypeAssistedChannelHandler.swift +++ b/Sources/NIOCore/TypeAssistedChannelHandler.swift @@ -30,6 +30,11 @@ extension _EmittingChannelHandler { public func wrapOutboundOut(_ value: OutboundOut) -> NIOAny { NIOAny(value) } + + @inlinable + public static func wrapOutboundOut(_ value: OutboundOut) -> NIOAny { + NIOAny(value) + } } /// `ChannelHandler` which handles inbound I/O events for a `Channel`. @@ -62,6 +67,16 @@ extension ChannelInboundHandler { public func wrapInboundOut(_ value: InboundOut) -> NIOAny { NIOAny(value) } + + @inlinable + public static func unwrapInboundIn(_ value: NIOAny) -> InboundIn { + value.forceAs() + } + + @inlinable + public static func wrapInboundOut(_ value: InboundOut) -> NIOAny { + NIOAny(value) + } } /// `ChannelHandler` which handles outbound I/O events or intercept an outbound I/O operation for a `Channel`. @@ -82,6 +97,11 @@ extension ChannelOutboundHandler { public func unwrapOutboundIn(_ value: NIOAny) -> OutboundIn { value.forceAs() } + + @inlinable + public static func unwrapOutboundIn(_ value: NIOAny) -> OutboundIn { + value.forceAs() + } } /// A combination of `ChannelInboundHandler` and `ChannelOutboundHandler`. diff --git a/Sources/NIOCrashTester/OutputGrepper.swift b/Sources/NIOCrashTester/OutputGrepper.swift index eb70639c3b..7802fe83b9 100644 --- a/Sources/NIOCrashTester/OutputGrepper.swift +++ b/Sources/NIOCrashTester/OutputGrepper.swift @@ -67,7 +67,7 @@ private final class GrepHandler: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let line = self.unwrapInboundIn(data) + let line = Self.unwrapInboundIn(data) if line.lowercased().contains("fatal error") || line.lowercased().contains("precondition failed") || line.lowercased().contains("assertion failed") { @@ -94,7 +94,7 @@ private struct NewlineFramer: ByteToMessageDecoder { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let firstNewline = buffer.readableBytesView.firstIndex(of: UInt8(ascii: "\n")) { let length = firstNewline - buffer.readerIndex + 1 - context.fireChannelRead(self.wrapInboundOut(String(buffer.readString(length: length)!.dropLast()))) + context.fireChannelRead(Self.wrapInboundOut(String(buffer.readString(length: length)!.dropLast()))) return .continue } else { return .needMoreData diff --git a/Sources/NIOEchoClient/main.swift b/Sources/NIOEchoClient/main.swift index 33f96e5cfe..5e846a1cba 100644 --- a/Sources/NIOEchoClient/main.swift +++ b/Sources/NIOEchoClient/main.swift @@ -29,11 +29,11 @@ private final class EchoHandler: ChannelInboundHandler { // We are connected. It's time to send the message to the server to initialize the ping-pong sequence. let buffer = context.channel.allocator.buffer(string: line) self.sendBytes = buffer.readableBytes - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var unwrappedInboundData = self.unwrapInboundIn(data) + var unwrappedInboundData = Self.unwrapInboundIn(data) self.sendBytes -= unwrappedInboundData.readableBytes receiveBuffer.writeBuffer(&unwrappedInboundData) diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index 4822120759..19bc6109ac 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -202,7 +202,7 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(var request): assert( !(request.headers.contains(name: "content-length") @@ -221,7 +221,7 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH } writeHead( - wrapOutboundOut: self.wrapOutboundOut, + wrapOutboundOut: Self.wrapOutboundOut, writeStartLine: { buffer in buffer.write(request: request) }, @@ -231,7 +231,7 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH ) case .body(let bodyPart): writeChunk( - wrapOutboundOut: self.wrapOutboundOut, + wrapOutboundOut: Self.wrapOutboundOut, context: context, isChunked: self.isChunked, chunk: bodyPart, @@ -239,7 +239,7 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH ) case .end(let trailers): writeTrailers( - wrapOutboundOut: self.wrapOutboundOut, + wrapOutboundOut: Self.wrapOutboundOut, context: context, isChunked: self.isChunked, trailers: trailers, @@ -292,7 +292,7 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(var response): assert( !(response.headers.contains(name: "content-length") @@ -312,7 +312,7 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel } writeHead( - wrapOutboundOut: self.wrapOutboundOut, + wrapOutboundOut: Self.wrapOutboundOut, writeStartLine: { buffer in buffer.write(response: response) }, @@ -322,7 +322,7 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel ) case .body(let bodyPart): writeChunk( - wrapOutboundOut: self.wrapOutboundOut, + wrapOutboundOut: Self.wrapOutboundOut, context: context, isChunked: self.isChunked, chunk: bodyPart, @@ -330,7 +330,7 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel ) case .end(let trailers): writeTrailers( - wrapOutboundOut: self.wrapOutboundOut, + wrapOutboundOut: Self.wrapOutboundOut, context: context, isChunked: self.isChunked, trailers: trailers, diff --git a/Sources/NIOHTTP1/HTTPHeaderValidator.swift b/Sources/NIOHTTP1/HTTPHeaderValidator.swift index ea2471637e..ad8a0b584d 100644 --- a/Sources/NIOHTTP1/HTTPHeaderValidator.swift +++ b/Sources/NIOHTTP1/HTTPHeaderValidator.swift @@ -29,7 +29,7 @@ public final class NIOHTTPRequestHeadersValidator: ChannelOutboundHandler, Remov public init() {} public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(let head): guard head.headers.areValidToSend else { promise?.fail(HTTPParserError.invalidHeaderToken) @@ -66,7 +66,7 @@ public final class NIOHTTPResponseHeadersValidator: ChannelOutboundHandler, Remo public init() {} public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(let head): guard head.headers.areValidToSend else { promise?.fail(HTTPParserError.invalidHeaderToken) diff --git a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift index 77925c3c40..c6626dd0e7 100644 --- a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift @@ -408,7 +408,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha "Received second response while waiting for first one to complete" ) debugOnly { - let res = self.unwrapOutboundIn(data) + let res = Self.unwrapOutboundIn(data) switch res { case .head(let head) where head.isInformational: self.checkAssertion(self.nextExpectedOutboundMessage == .head) @@ -425,12 +425,12 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha var startReadingAgain = false - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(var head) where self.lifecycleState != .acceptingEvents: if head.isKeepAlive { head.headers.replaceOrAdd(name: "connection", value: "close") } - context.write(self.wrapOutboundOut(.head(head)), promise: promise) + context.write(Self.wrapOutboundOut(.head(head)), promise: promise) case .end: startReadingAgain = true @@ -648,7 +648,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha let maybeFirstHead = self.eventBuffer.firstIndex(where: { element in switch element { case .channelRead(let read): - switch self.unwrapInboundIn(read) { + switch Self.unwrapInboundIn(read) { case .head: return true case .body, .end: diff --git a/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift b/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift index eb985eec11..e3ad137410 100644 --- a/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift @@ -46,8 +46,8 @@ public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, Removab if !self.hasUnterminatedResponse { let headers = HTTPHeaders([("Connection", "close"), ("Content-Length", "0")]) let head = HTTPResponseHead(version: .http1_1, status: .badRequest, headers: headers) - context.write(self.wrapOutboundOut(.head(head)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(head)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } // Now pass the error on in case someone else wants to see it. @@ -55,7 +55,7 @@ public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, Removab } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let res = self.unwrapOutboundIn(data) + let res = Self.unwrapOutboundIn(data) switch res { case .head(let head) where head.isInformational: precondition(!self.hasUnterminatedResponse) diff --git a/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift index 1d28fe58c0..0c691cc5df 100644 --- a/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift @@ -113,7 +113,7 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha return } - let requestPart = unwrapInboundIn(data) + let requestPart = Self.unwrapInboundIn(data) switch self.upgradeState { case .idle: @@ -344,14 +344,14 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha // We haven't seen the first request .end. That means we're not buffering anything, and we can // just deliver data. assert(self.receivedMessages.isEmpty) - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) } else { // This is trickier. We've seen the first request .end, so we now need to deliver the .head we // got passed, as well as the .end we swallowed, and any buffered parts. While we're doing this // we may be re-entrantly called, which will cause us to buffer new parts. To make that safe, we // must ensure we aren't holding the buffer mutably, so no for loop for us. - context.fireChannelRead(self.wrapInboundOut(data)) - context.fireChannelRead(self.wrapInboundOut(.end(nil))) + context.fireChannelRead(Self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(.end(nil))) } context.fireChannelReadComplete() diff --git a/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift b/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift index ae0b6957f3..b092512f16 100644 --- a/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift @@ -175,7 +175,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC private func addHeadersToOutboundOut(data: NIOAny) -> NIOAny { - let interceptedOutgoingRequest = self.unwrapOutboundIn(data) + let interceptedOutgoingRequest = Self.unwrapOutboundIn(data) if case .head(var requestHead) = interceptedOutgoingRequest { @@ -183,7 +183,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC self.addConnectionHeaders(to: &requestHead) self.addUpgradeHeaders(to: &requestHead) - return self.wrapOutboundOut(.head(requestHead)) + return Self.wrapOutboundOut(.head(requestHead)) } return data @@ -214,7 +214,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC return } - let responsePart = unwrapInboundIn(data) + let responsePart = Self.unwrapInboundIn(data) switch self.upgradeState { case .awaitingConfirmationResponse: @@ -394,7 +394,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC } assert(self.receivedMessages.isEmpty) - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) // We've delivered the data. We can now remove ourselves, which should happen synchronously. context.pipeline.removeHandler(context: context, promise: nil) diff --git a/Sources/NIOHTTP1/NIOHTTPObjectAggregator.swift b/Sources/NIOHTTP1/NIOHTTPObjectAggregator.swift index 67c60b5b02..3821e6e2b4 100644 --- a/Sources/NIOHTTP1/NIOHTTPObjectAggregator.swift +++ b/Sources/NIOHTTP1/NIOHTTPObjectAggregator.swift @@ -198,7 +198,7 @@ public final class NIOHTTPServerRequestAggregator: ChannelInboundHandler, Remova } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let msg = self.unwrapInboundIn(data) + let msg = Self.unwrapInboundIn(data) var serverResponse: HTTPResponseHead? = nil do { @@ -224,8 +224,8 @@ public final class NIOHTTPServerRequestAggregator: ChannelInboundHandler, Remova // Generated a server response to send back if let response = serverResponse { - context.write(self.wrapOutboundOut(.head(response)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) if response.status == .payloadTooLarge { // If indicated content length is too large self.state.handlingOversizeMessage() @@ -345,7 +345,7 @@ public final class NIOHTTPClientResponseAggregator: ChannelInboundHandler, Remov } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let msg = self.unwrapInboundIn(data) + let msg = Self.unwrapInboundIn(data) do { switch msg { diff --git a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift index 5f6ba3e376..30f168c4e4 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift @@ -141,9 +141,9 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch public func channelActive(context: ChannelHandlerContext) { switch self.stateMachine.channelActive() { case .writeUpgradeRequest: - context.write(self.wrapOutboundOut(.head(self.upgradeRequestHead)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(.init()))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(self.upgradeRequestHead)), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(.init()))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) case .none: break @@ -179,7 +179,7 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch public func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch self.stateMachine.channelReadData(data) { case .unwrapData: - let responsePart = self.unwrapInboundIn(data) + let responsePart = Self.unwrapInboundIn(data) self.channelRead(context: context, responsePart: responsePart) case .fireChannelRead: diff --git a/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift index 63d8823322..dd08789a6d 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift @@ -143,7 +143,7 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch public func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch self.stateMachine.channelReadData(data) { case .unwrapData: - let requestPart = self.unwrapInboundIn(data) + let requestPart = Self.unwrapInboundIn(data) self.channelRead(context: context, requestPart: requestPart) case .fireChannelRead: diff --git a/Sources/NIOHTTP1Client/main.swift b/Sources/NIOHTTP1Client/main.swift index fa061fd1f3..4afd26600b 100644 --- a/Sources/NIOHTTP1Client/main.swift +++ b/Sources/NIOHTTP1Client/main.swift @@ -44,16 +44,16 @@ private final class HTTPEchoHandler: ChannelInboundHandler { headers: headers ) - context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) + context.write(Self.wrapOutboundOut(.head(requestHead)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let clientResponse = self.unwrapInboundIn(data) + let clientResponse = Self.unwrapInboundIn(data) switch clientResponse { case .head(let responseHead): diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index 1f908cfb3e..728512fac8 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -133,7 +133,7 @@ private final class HTTPHandler: ChannelInboundHandler { var headers = HTTPHeaders() headers.add(name: "Content-Length", value: "\(response.utf8.count)") context.write( - self.wrapOutboundOut( + Self.wrapOutboundOut( .head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers)) ), promise: nil @@ -157,7 +157,7 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.clear() } else { context.writeAndFlush( - self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), + Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil ) } @@ -165,7 +165,7 @@ private final class HTTPHandler: ChannelInboundHandler { if balloonInMemory { self.buffer.writeBuffer(&buf) } else { - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) } case .end: self.state.requestComplete() @@ -173,7 +173,7 @@ private final class HTTPHandler: ChannelInboundHandler { var headers = HTTPHeaders() headers.add(name: "Content-Length", value: "\(self.buffer.readableBytes)") context.write( - self.wrapOutboundOut( + Self.wrapOutboundOut( .head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers)) ), promise: nil @@ -199,7 +199,7 @@ private final class HTTPHandler: ChannelInboundHandler { self.keepAlive = request.isKeepAlive self.state.requestReceived() context.writeAndFlush( - self.wrapOutboundOut(.head(httpResponseHead(request: request, status: statusCode))), + Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: statusCode))), promise: nil ) case .body(buffer: _): @@ -209,7 +209,7 @@ private final class HTTPHandler: ChannelInboundHandler { context.eventLoop.scheduleTask(in: delay) { () -> Void in var buf = context.channel.allocator.buffer(capacity: string.utf8.count) buf.writeString(string) - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) var trailers: HTTPHeaders? = nil if let trailer = trailer { trailers = HTTPHeaders() @@ -231,14 +231,14 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.clear() self.continuousCount += 1 self.buffer.writeString("line \(self.continuousCount)\n") - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).map { + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).map { context.eventLoop.scheduleTask(in: .milliseconds(400), doNext) }.whenFailure { (_: Error) in self.completeResponse(context, trailers: nil, promise: nil) } } context.writeAndFlush( - self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), + Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil ) doNext() @@ -264,7 +264,7 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.clear() self.buffer.writeString(strings[self.continuousCount]) self.continuousCount += 1 - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).whenSuccess { + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).whenSuccess { if self.continuousCount < strings.count { context.eventLoop.scheduleTask(in: delay, doNext) } else { @@ -273,7 +273,7 @@ private final class HTTPHandler: ChannelInboundHandler { } } context.writeAndFlush( - self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), + Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil ) doNext() @@ -376,9 +376,9 @@ private final class HTTPHandler: ChannelInboundHandler { }() body.writeString("\(error)") body.writeStaticString("\r\n") - context.write(self.wrapOutboundOut(.head(response)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(body))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(body))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) context.channel.close(promise: nil) } @@ -395,7 +395,7 @@ private final class HTTPHandler: ChannelInboundHandler { self.state.requestReceived() guard !request.uri.containsDotDot() else { let response = httpResponseHead(request: request, status: .forbidden) - context.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) self.completeResponse(context, trailers: nil, promise: nil) return } @@ -411,7 +411,7 @@ private final class HTTPHandler: ChannelInboundHandler { let response = responseHead(request: request, fileRegion: region) if region.readableBytes == 0 { responseStarted = true - context.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) } return self.fileIO.readChunked( fileRegion: region, @@ -421,9 +421,9 @@ private final class HTTPHandler: ChannelInboundHandler { ) { buffer in if !responseStarted { responseStarted = true - context.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) } - return context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(buffer)))) + return context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(buffer)))) }.flatMap { () -> EventLoopFuture in let p = context.eventLoop.makePromise(of: Void.self) self.completeResponse(context, trailers: nil, promise: p) @@ -431,12 +431,12 @@ private final class HTTPHandler: ChannelInboundHandler { }.flatMapError { error in if !responseStarted { let response = httpResponseHead(request: request, status: .ok) - context.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) var buffer = context.channel.allocator.buffer(capacity: 100) buffer.writeString("fail: \(error)") - context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) self.state.responseComplete() - return context.writeAndFlush(self.wrapOutboundOut(.end(nil))) + return context.writeAndFlush(Self.wrapOutboundOut(.end(nil))) } else { return context.close() } @@ -445,8 +445,8 @@ private final class HTTPHandler: ChannelInboundHandler { } case .sendfile: let response = responseHead(request: request, fileRegion: region) - context.write(self.wrapOutboundOut(.head(response)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.body(.fileRegion(region)))).flatMap { + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.body(.fileRegion(region)))).flatMap { let p = context.eventLoop.makePromise(of: Void.self) self.completeResponse(context, trailers: nil, promise: p) return p.futureResult @@ -477,11 +477,11 @@ private final class HTTPHandler: ChannelInboundHandler { } self.handler = nil - context.writeAndFlush(self.wrapOutboundOut(.end(trailers)), promise: promise) + context.writeAndFlush(Self.wrapOutboundOut(.end(trailers)), promise: promise) } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let reqPart = self.unwrapInboundIn(data) + let reqPart = Self.unwrapInboundIn(data) if let handler = self.handler { handler(context, reqPart) return @@ -511,13 +511,13 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.writeString(self.defaultResponse) responseHead.headers.add(name: "content-length", value: "\(self.buffer!.readableBytes)") let response = HTTPServerResponsePart.head(responseHead) - context.write(self.wrapOutboundOut(response), promise: nil) + context.write(Self.wrapOutboundOut(response), promise: nil) case .body: break case .end: self.state.requestComplete() let content = HTTPServerResponsePart.body(.byteBuffer(buffer!.slice())) - context.write(self.wrapOutboundOut(content), promise: nil) + context.write(Self.wrapOutboundOut(content), promise: nil) self.completeResponse(context, trailers: nil, promise: nil) } } diff --git a/Sources/NIOMulticastChat/main.swift b/Sources/NIOMulticastChat/main.swift index f289a43ba3..60818b0f3f 100644 --- a/Sources/NIOMulticastChat/main.swift +++ b/Sources/NIOMulticastChat/main.swift @@ -19,7 +19,7 @@ private final class ChatMessageDecoder: ChannelInboundHandler { public typealias InboundIn = AddressedEnvelope public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let envelope = self.unwrapInboundIn(data) + let envelope = Self.unwrapInboundIn(data) var buffer = envelope.data // To begin with, the chat messages are simply whole datagrams, no other length. @@ -37,10 +37,10 @@ private final class ChatMessageEncoder: ChannelOutboundHandler { public typealias OutboundOut = AddressedEnvelope func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let message = self.unwrapOutboundIn(data) + let message = Self.unwrapOutboundIn(data) let buffer = context.channel.allocator.buffer(string: message.data) context.write( - self.wrapOutboundOut(AddressedEnvelope(remoteAddress: message.remoteAddress, data: buffer)), + Self.wrapOutboundOut(AddressedEnvelope(remoteAddress: message.remoteAddress, data: buffer)), promise: promise ) } diff --git a/Sources/NIOPerformanceTester/TCPThroughputBenchmark.swift b/Sources/NIOPerformanceTester/TCPThroughputBenchmark.swift index 124eee18a9..e4b836ba62 100644 --- a/Sources/NIOPerformanceTester/TCPThroughputBenchmark.swift +++ b/Sources/NIOPerformanceTester/TCPThroughputBenchmark.swift @@ -52,7 +52,7 @@ final class TCPThroughputBenchmark: Benchmark { public func send(_ message: ByteBuffer, times count: Int) { for _ in 0.. DecodingState { if let messageSize = buffer.getInteger(at: buffer.readerIndex, as: UInt16.self) { if buffer.readableBytes >= messageSize { - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: Int(messageSize))!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: Int(messageSize))!)) return .continue } } diff --git a/Sources/NIOPerformanceTester/UDPBenchmark.swift b/Sources/NIOPerformanceTester/UDPBenchmark.swift index dff518ad17..090b261bb8 100644 --- a/Sources/NIOPerformanceTester/UDPBenchmark.swift +++ b/Sources/NIOPerformanceTester/UDPBenchmark.swift @@ -258,7 +258,7 @@ extension UDPBenchmark { remoteAddress: self.config.remoteAddress, data: self.config.request ) - context.write(self.wrapOutboundOut(envolope), promise: nil) + context.write(Self.wrapOutboundOut(envolope), promise: nil) if flush { context.flush() } diff --git a/Sources/NIOPerformanceTester/main.swift b/Sources/NIOPerformanceTester/main.swift index 849d6edd9f..992ad50ad8 100644 --- a/Sources/NIOPerformanceTester/main.swift +++ b/Sources/NIOPerformanceTester/main.swift @@ -127,14 +127,14 @@ private final class SimpleHTTPServer: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - if case .head(let req) = self.unwrapInboundIn(data) { + if case .head(let req) = Self.unwrapInboundIn(data) { switch req.uri { case "/perf-test-1": var buffer = context.channel.allocator.buffer(capacity: self.cachedBody.count) buffer.writeBytes(self.cachedBody) - context.write(self.wrapOutboundOut(.head(self.cachedHead)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(self.cachedHead)), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) return case "/perf-test-2": var req = HTTPResponseHead(version: .http1_1, status: .ok) @@ -142,8 +142,8 @@ private final class SimpleHTTPServer: ChannelInboundHandler { req.headers.add(name: "X-ResponseHeader-\(i)", value: "foo") } req.headers.add(name: "content-length", value: "0") - context.write(self.wrapOutboundOut(.head(req)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(req)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) return default: fatalError("unknown uri \(req.uri)") @@ -199,7 +199,7 @@ final class RepeatedRequests: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let reqPart = self.unwrapInboundIn(data) + let reqPart = Self.unwrapInboundIn(data) if case .end(nil) = reqPart { if self.remainingNumberOfRequests <= 0 { context.channel.close().map { self.doneRequests }.cascade(to: self.isDonePromise) @@ -207,8 +207,8 @@ final class RepeatedRequests: ChannelInboundHandler { self.doneRequests += 1 self.remainingNumberOfRequests -= 1 - context.write(self.wrapOutboundOut(.head(head)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(head)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } } } @@ -601,7 +601,7 @@ try measureAndPrint(desc: "no-net_http1_1k_reqs_1_conn") { } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - var buf = self.unwrapOutboundIn(data) + var buf = Self.unwrapOutboundIn(data) if self.expectedResponseBuffer == nil { self.expectedResponseBuffer = buf } diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index 9db90c1fa6..6deaae1e1c 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -453,7 +453,7 @@ public final class ServerBootstrap { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let accepted = self.unwrapInboundIn(data) + let accepted = Self.unwrapInboundIn(data) let ctxEventLoop = context.eventLoop let childEventLoop = accepted.eventLoop let childChannelInit = self.childChannelInit ?? { (_: Channel) in childEventLoop.makeSucceededFuture(()) } diff --git a/Sources/NIOTCPEchoClient/Client.swift b/Sources/NIOTCPEchoClient/Client.swift index 16f2d5da4e..e624a78667 100644 --- a/Sources/NIOTCPEchoClient/Client.swift +++ b/Sources/NIOTCPEchoClient/Client.swift @@ -100,7 +100,7 @@ private final class NewlineDelimiterCoder: ByteToMessageDecoder, MessageToByteEn if let firstLine = readableBytes.firstIndex(of: self.newLine).map({ readableBytes[..<$0] }) { buffer.moveReaderIndex(forwardBy: firstLine.count + 1) // Fire a read without a newline - context.fireChannelRead(self.wrapInboundOut(String(buffer: ByteBuffer(firstLine)))) + context.fireChannelRead(Self.wrapInboundOut(String(buffer: ByteBuffer(firstLine)))) return .continue } else { return .needMoreData diff --git a/Sources/NIOTCPEchoServer/Server.swift b/Sources/NIOTCPEchoServer/Server.swift index f830cd4e0f..451d687b89 100644 --- a/Sources/NIOTCPEchoServer/Server.swift +++ b/Sources/NIOTCPEchoServer/Server.swift @@ -110,7 +110,7 @@ private final class NewlineDelimiterCoder: ByteToMessageDecoder, MessageToByteEn if let firstLine = readableBytes.firstIndex(of: self.newLine).map({ readableBytes[..<$0] }) { buffer.moveReaderIndex(forwardBy: firstLine.count + 1) // Fire a read without a newline - context.fireChannelRead(self.wrapInboundOut(String(buffer: ByteBuffer(firstLine)))) + context.fireChannelRead(Self.wrapInboundOut(String(buffer: ByteBuffer(firstLine)))) return .continue } else { return .needMoreData diff --git a/Sources/NIOTestUtils/NIOHTTP1TestServer.swift b/Sources/NIOTestUtils/NIOHTTP1TestServer.swift index 568f910c0a..b4326f5c58 100644 --- a/Sources/NIOTestUtils/NIOHTTP1TestServer.swift +++ b/Sources/NIOTestUtils/NIOHTTP1TestServer.swift @@ -70,15 +70,15 @@ private final class WebServerHandler: ChannelDuplexHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.webServer.pushChannelRead(self.unwrapInboundIn(data)) + self.webServer.pushChannelRead(Self.unwrapInboundIn(data)) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(var head): head.headers.replaceOrAdd(name: "connection", value: "close") head.headers.remove(name: "keep-alive") - context.write(self.wrapOutboundOut(.head(head)), promise: promise) + context.write(Self.wrapOutboundOut(.head(head)), promise: promise) case .body: context.write(data, promise: promise) case .end: @@ -96,14 +96,14 @@ private final class AggregateBodyHandler: ChannelInboundHandler { var receivedSoFar: ByteBuffer? = nil func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head: context.fireChannelRead(data) case .body(var buffer): self.receivedSoFar.setOrWriteBuffer(&buffer) case .end: if let receivedSoFar = self.receivedSoFar { - context.fireChannelRead(self.wrapInboundOut(.body(receivedSoFar))) + context.fireChannelRead(Self.wrapInboundOut(.body(receivedSoFar))) } context.fireChannelRead(data) } diff --git a/Sources/NIOUDPEchoClient/main.swift b/Sources/NIOUDPEchoClient/main.swift index c1c68c718a..f0348b7cd6 100644 --- a/Sources/NIOUDPEchoClient/main.swift +++ b/Sources/NIOUDPEchoClient/main.swift @@ -43,7 +43,7 @@ private final class EchoHandler: ChannelInboundHandler { // Forward the data. let envelope = AddressedEnvelope(remoteAddress: remoteAddress, data: buffer) - context.writeAndFlush(self.wrapOutboundOut(envelope), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(envelope), promise: nil) } catch { print("Could not resolve remote address") @@ -51,7 +51,7 @@ private final class EchoHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let envelope = self.unwrapInboundIn(data) + let envelope = Self.unwrapInboundIn(data) let byteBuffer = envelope.data self.numBytes -= byteBuffer.readableBytes diff --git a/Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift b/Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift index 008d82a838..1f929e8cae 100644 --- a/Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift +++ b/Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift @@ -53,7 +53,7 @@ public final class NIOWebSocketFrameAggregator: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = unwrapInboundIn(data) + let frame = Self.unwrapInboundIn(data) do { switch frame.opcode { case .continuation: diff --git a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift index bb3512acc7..583cdbec66 100644 --- a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift @@ -262,7 +262,7 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { while true { switch parser.parseStep(&buffer) { case .result(let frame): - context.fireChannelRead(self.wrapInboundOut(frame)) + context.fireChannelRead(Self.wrapInboundOut(frame)) return .continue case .continueParsing: try self.parser.validateState(maxFrameSize: self.maxFrameSize) diff --git a/Sources/NIOWebSocket/WebSocketFrameEncoder.swift b/Sources/NIOWebSocket/WebSocketFrameEncoder.swift index 565be00058..8bac7446dc 100644 --- a/Sources/NIOWebSocket/WebSocketFrameEncoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameEncoder.swift @@ -59,7 +59,7 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let data = self.unwrapOutboundIn(data) + let data = Self.unwrapOutboundIn(data) // First, we explode the frame structure and apply the mask. let frameHeader = FrameHeader(frame: data) @@ -77,13 +77,13 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { if !unwrappedExtensionData.prependFrameHeaderIfPossible(frameHeader) { self.writeSeparateHeaderBuffer(frameHeader, context: context) } - context.write(self.wrapOutboundOut(unwrappedExtensionData), promise: nil) + context.write(Self.wrapOutboundOut(unwrappedExtensionData), promise: nil) } else if !applicationData.prependFrameHeaderIfPossible(frameHeader) { self.writeSeparateHeaderBuffer(frameHeader, context: context) } // Ok, now we need to write the application data buffer. - context.write(self.wrapOutboundOut(applicationData), promise: promise) + context.write(Self.wrapOutboundOut(applicationData), promise: promise) } /// Applies the websocket masking operation based on the passed byte buffers. @@ -119,7 +119,7 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { // Ok, frame header away! Before we send it we save it back onto ourselves in case we get recursively called. self.headerBuffer = buffer - context.write(self.wrapOutboundOut(buffer), promise: nil) + context.write(Self.wrapOutboundOut(buffer), promise: nil) } } diff --git a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift index 2be44b3468..89714f4c90 100644 --- a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift +++ b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift @@ -33,7 +33,7 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { opcode: .connectionClose, data: data ) - context.writeAndFlush(self.wrapOutboundOut(frame)).whenComplete { (_: Result) in + context.writeAndFlush(Self.wrapOutboundOut(frame)).whenComplete { (_: Result) in context.close(promise: nil) } } diff --git a/Sources/NIOWebSocketServer/Server.swift b/Sources/NIOWebSocketServer/Server.swift index 7842ee3d24..6a9252b0e9 100644 --- a/Sources/NIOWebSocketServer/Server.swift +++ b/Sources/NIOWebSocketServer/Server.swift @@ -277,14 +277,14 @@ final class HTTPByteBufferResponsePartHandler: ChannelOutboundHandler { typealias OutboundOut = HTTPServerResponsePart func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let part = self.unwrapOutboundIn(data) + let part = Self.unwrapOutboundIn(data) switch part { case .head(let head): - context.write(self.wrapOutboundOut(.head(head)), promise: promise) + context.write(Self.wrapOutboundOut(.head(head)), promise: promise) case .body(let buffer): - context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: promise) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: promise) case .end(let trailers): - context.write(self.wrapOutboundOut(.end(trailers)), promise: promise) + context.write(Self.wrapOutboundOut(.end(trailers)), promise: promise) } } } diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncSequenceTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncSequenceTests.swift index dded3fbb91..3720976224 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncSequenceTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncSequenceTests.swift @@ -279,7 +279,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence._throwingSequence._storage._setDidSuspend { suspended.fulfill() } async let element = sequence.first { _ in true } @@ -363,7 +363,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence!._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence!._throwingSequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { let element = await sequence!.first { _ in true } @@ -453,7 +453,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence._throwingSequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -475,7 +475,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let resumed = expectation(description: "task resumed") let cancelled = expectation(description: "task cancelled") - sequence._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence._throwingSequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -503,7 +503,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence._throwingSequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift index 8a9cd2e918..95760bd411 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift @@ -78,7 +78,7 @@ final class NIOAsyncWriterTests: XCTestCase { ) self.writer = newWriter.writer self.sink = newWriter.sink - self.sink._storage._didSuspend = self.delegate.didSuspend + self.sink._storage._setDidSuspend { self.delegate.didSuspend() } } override func tearDown() { diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOThrowingAsyncSequenceTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOThrowingAsyncSequenceTests.swift index fea9f05929..5d4f8d1443 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOThrowingAsyncSequenceTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOThrowingAsyncSequenceTests.swift @@ -110,7 +110,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { try await sequence.first { _ in true } @@ -138,7 +138,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { try await sequence.first { _ in true } @@ -166,7 +166,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { await withThrowingTaskGroup(of: Void.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { _ = try await sequence.first { _ in true } @@ -191,7 +191,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { await withThrowingTaskGroup(of: Void.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { _ = try await sequence.first { _ in true } @@ -256,7 +256,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { let element = try await sequence.first { _ in true } @@ -339,7 +339,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { try await withThrowingTaskGroup(of: Void.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { _ = try await sequence.first { _ in true } @@ -458,7 +458,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence!._storage._didSuspend = { suspended.fulfill() } + sequence!._storage._setDidSuspend { suspended.fulfill() } group.addTask { let element = try await sequence!.first { _ in true } @@ -550,7 +550,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -581,7 +581,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = new.sequence let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -605,7 +605,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let resumed = expectation(description: "task resumed") let cancelled = expectation(description: "task cancelled") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -633,7 +633,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -707,7 +707,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } Task { // Would prefer to use async let _ here but that is not allowed yet @@ -725,7 +725,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } Task { // Would prefer to use async let _ here but that is not allowed yet @@ -745,7 +745,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } Task { // Would prefer to use async let _ here but that is not allowed yet @@ -765,7 +765,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } Task { // Would prefer to use async let _ here but that is not allowed yet diff --git a/Tests/NIOCoreTests/SingleStepByteToMessageDecoderTest.swift b/Tests/NIOCoreTests/SingleStepByteToMessageDecoderTest.swift index 4440e60821..60921984db 100644 --- a/Tests/NIOCoreTests/SingleStepByteToMessageDecoderTest.swift +++ b/Tests/NIOCoreTests/SingleStepByteToMessageDecoderTest.swift @@ -430,14 +430,14 @@ public final class NIOSingleStepByteToMessageDecoderTest: XCTestCase { self.processor = NIOSingleStepByteToMessageProcessor(OneByteStringDecoder()) } do { - try self.processor!.process(buffer: self.unwrapInboundIn(data)) { message in + try self.processor!.process(buffer: Self.unwrapInboundIn(data)) { message in self.produced += 1 // Produce an extra write the first time we are called to test reentrancy if self.produced == 1 { let buf = ByteBuffer(string: "X") XCTAssertNoThrow(try (context.channel as! EmbeddedChannel).writeInbound(buf)) } - context.fireChannelRead(self.wrapInboundOut(message)) + context.fireChannelRead(Self.wrapInboundOut(message)) } } catch { context.fireErrorCaught(error) diff --git a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift index ce1ed32a63..537fa0740a 100644 --- a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift @@ -248,13 +248,13 @@ extension ChannelInboundHandler where OutboundOut == HTTPClientRequestPart { headers: headers ) - context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) + context.write(Self.wrapOutboundOut(.head(requestHead)), promise: nil) let emptyBuffer = context.channel.allocator.buffer(capacity: 0) let body = HTTPClientRequestPart.body(.byteBuffer(emptyBuffer)) context.write(self.wrapOutboundOut(body), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } } diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift index ef1365e28e..273ae2743e 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift @@ -25,7 +25,7 @@ private class MessageEndHandler: ChannelInboun var seenHead = false func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head: XCTAssertFalse(self.seenHead) self.seenHead = true @@ -85,7 +85,7 @@ class HTTPDecoderLengthTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head(let h): self.response = h case .end: diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift index b56916aeaf..8d993715da 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift @@ -143,7 +143,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let h): XCTAssertEqual("/SomeURL", h.uri) @@ -186,7 +186,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .end: // ignore @@ -223,7 +223,7 @@ class HTTPDecoderTest: XCTestCase { var called: Bool = false func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) XCTAssertEqual("XXXX", buffer.readString(length: buffer.readableBytes)!) self.called = true } @@ -247,7 +247,7 @@ class HTTPDecoderTest: XCTestCase { let collector = ByteCollector() func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .end: _ = context.pipeline.removeHandler(self).flatMap { _ in @@ -289,7 +289,7 @@ class HTTPDecoderTest: XCTestCase { var called: Bool = false func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) XCTAssertEqual("XXXX", buffer.readString(length: buffer.readableBytes)!) self.called = true } @@ -318,7 +318,7 @@ class HTTPDecoderTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .end: _ = context.pipeline.removeHandler(self).flatMap { _ in @@ -642,7 +642,7 @@ class HTTPDecoderTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let head): XCTAssertEqual(.OPTIONS, head.method) @@ -672,7 +672,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let head): XCTAssertEqual(.OPTIONS, head.method) @@ -717,7 +717,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let head): XCTAssertEqual(.OPTIONS, head.method) @@ -764,7 +764,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let head): XCTAssertEqual(.OPTIONS, head.method) diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index 7dd60af621..94ab77a4b2 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -50,7 +50,7 @@ internal class ArrayAccumulationHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.receiveds.append(self.unwrapInboundIn(data)) + self.receiveds.append(Self.unwrapInboundIn(data)) } public func channelUnregistered(context: ChannelHandlerContext) { @@ -109,7 +109,7 @@ class HTTPServerClientTest: XCTestCase { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head(let req): switch req.uri { case "/helloworld": @@ -118,15 +118,15 @@ class HTTPServerClientTest: XCTestCase { head.headers.add(name: "Content-Length", value: "\(replyString.utf8.count)") head.headers.add(name: "Connection", value: "close") let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r), promise: nil) + context.write(Self.wrapOutboundOut(r), promise: nil) var b = context.channel.allocator.buffer(capacity: replyString.count) b.writeString(replyString) let outbound = self.outboundBody(b) - context.write(self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in + context.write(Self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in outbound.destructor() } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -136,7 +136,7 @@ class HTTPServerClientTest: XCTestCase { var head = HTTPResponseHead(version: req.version, status: .ok) head.headers.add(name: "Connection", value: "close") let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(Self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } var b = context.channel.allocator.buffer(capacity: 1024) @@ -145,13 +145,13 @@ class HTTPServerClientTest: XCTestCase { b.writeString("\(i)") let outbound = self.outboundBody(b) - context.write(self.wrapOutboundOut(outbound.body)).recover { error in + context.write(Self.wrapOutboundOut(outbound.body)).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in outbound.destructor() } } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -162,7 +162,7 @@ class HTTPServerClientTest: XCTestCase { head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Transfer-Encoding", value: "chunked") let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(Self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } var b = context.channel.allocator.buffer(capacity: 1024) @@ -171,7 +171,7 @@ class HTTPServerClientTest: XCTestCase { b.writeString("\(i)") let outbound = self.outboundBody(b) - context.write(self.wrapOutboundOut(outbound.body)).recover { error in + context.write(Self.wrapOutboundOut(outbound.body)).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in outbound.destructor() @@ -181,7 +181,7 @@ class HTTPServerClientTest: XCTestCase { var trailers = HTTPHeaders() trailers.add(name: "X-URL-Path", value: "/trailers") trailers.add(name: "X-Should-Trail", value: "sure") - context.write(self.wrapOutboundOut(.end(trailers))).recover { error in + context.write(Self.wrapOutboundOut(.end(trailers))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -196,16 +196,16 @@ class HTTPServerClientTest: XCTestCase { head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Content-Length", value: "\(HTTPServerClientTest.massiveResponseLength)") let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(Self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } let outbound = self.outboundBody(buf) - context.writeAndFlush(self.wrapOutboundOut(outbound.body)).recover { error in + context.writeAndFlush(Self.wrapOutboundOut(outbound.body)).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in outbound.destructor() } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -215,10 +215,10 @@ class HTTPServerClientTest: XCTestCase { var head = HTTPResponseHead(version: req.version, status: .ok) head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Content-Length", value: "5000") - context.write(self.wrapOutboundOut(.head(head))).whenFailure { error in + context.write(Self.wrapOutboundOut(.head(head))).whenFailure { error in XCTFail("unexpected error \(error)") } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -227,10 +227,10 @@ class HTTPServerClientTest: XCTestCase { case "/204": var head = HTTPResponseHead(version: req.version, status: .noContent) head.headers.add(name: "Connection", value: "keep-alive") - context.write(self.wrapOutboundOut(.head(head))).whenFailure { error in + context.write(Self.wrapOutboundOut(.head(head))).whenFailure { error in XCTFail("unexpected error \(error)") } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -240,15 +240,15 @@ class HTTPServerClientTest: XCTestCase { let replyString = "Hello World!\r\n" let head = HTTPResponseHead(version: req.version, status: .ok) let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r), promise: nil) + context.write(Self.wrapOutboundOut(r), promise: nil) var b = context.channel.allocator.buffer(capacity: replyString.count) b.writeString(replyString) let outbound = self.outboundBody(b) - context.write(self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in + context.write(Self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in outbound.destructor() } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -257,18 +257,18 @@ class HTTPServerClientTest: XCTestCase { case "/zero-length-body-part": let r = HTTPServerResponsePart.head(.init(version: req.version, status: .ok)) - context.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(Self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer())))).whenFailure { error in + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer())))).whenFailure { error in XCTFail("unexpected error \(error)") } - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer(string: "Hello World"))))) + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer(string: "Hello World"))))) .whenFailure { error in XCTFail("unexpected error \(error)") } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true diff --git a/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift b/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift index 2de981fecc..7029e2f73e 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift @@ -40,7 +40,7 @@ private final class ReadRecorder: ChannelInboundHandler { public var reads: [Event] = [] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.reads.append(.channelRead(self.unwrapInboundIn(data))) + self.reads.append(.channelRead(Self.unwrapInboundIn(data))) context.fireChannelRead(data) } @@ -60,7 +60,7 @@ private final class WriteRecorder: ChannelOutboundHandler { public var writes: [HTTPServerResponsePart] = [] func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - self.writes.append(self.unwrapOutboundIn(data)) + self.writes.append(Self.unwrapOutboundIn(data)) context.write(data, promise: promise) } @@ -485,7 +485,7 @@ class HTTPServerPipelineHandlerTest: XCTestCase { var state: State = .req1HeadExpected func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let req = self.unwrapInboundIn(data) + let req = Self.unwrapInboundIn(data) switch req { case .head(let head): // except for "req_1", we always send the .end straight away @@ -509,11 +509,11 @@ class HTTPServerPipelineHandlerTest: XCTestCase { XCTFail("didn't expect \(head)") } context.write( - self.wrapOutboundOut(.head(HTTPResponseHead(version: .http1_1, status: .ok))), + Self.wrapOutboundOut(.head(HTTPResponseHead(version: .http1_1, status: .ok))), promise: nil ) if sendEnd { - context.write(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.end(nil)), promise: nil) } context.flush() case .end: @@ -912,13 +912,13 @@ class HTTPServerPipelineHandlerTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head: // We dispatch this to the event loop so that it doesn't happen immediately but rather can be // run from the driving test code whenever it wants by running the EmbeddedEventLoop. context.eventLoop.execute { context.writeAndFlush( - self.wrapOutboundOut( + Self.wrapOutboundOut( .head( .init( version: .http1_1, @@ -937,7 +937,7 @@ class HTTPServerPipelineHandlerTest: XCTestCase { // We dispatch this to the event loop so that it doesn't happen immediately but rather can be // run from the driving test code whenever it wants by running the EmbeddedEventLoop. context.eventLoop.execute { - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } XCTAssertEqual(.reqEndExpected, self.state) self.state = .errorExpected diff --git a/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift b/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift index 122e079df6..93fcaf05fe 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift @@ -118,7 +118,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { private var nextExpected: NextExpectedState = .head func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let req = self.unwrapInboundIn(data) + let req = Self.unwrapInboundIn(data) switch req { case .head: XCTAssertEqual(.head, self.nextExpected) @@ -130,7 +130,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { headers: .init([("Content-Length", "0")]) ) ) - context.writeAndFlush(self.wrapOutboundOut(res), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(res), promise: nil) default: XCTAssertEqual(.end, self.nextExpected) self.nextExpected = .none diff --git a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift index bee9bf602b..343b6b9138 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift @@ -146,7 +146,7 @@ private class SingleHTTPResponseAccumulator: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) self.receiveds.append(buffer) if let finalBytes = buffer.getBytes(at: buffer.writerIndex - 4, length: 4), finalBytes == [0x0D, 0x0A, 0x0D, 0x0A] @@ -450,7 +450,7 @@ private class DataRecorder: ChannelInboundHandler { private var data: [T] = [] public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let datum = self.unwrapInboundIn(data) + let datum = Self.unwrapInboundIn(data) self.data.append(datum) } @@ -1331,7 +1331,7 @@ class HTTPServerUpgradeTestCase: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) let stringRead = buf.readString(length: buf.readableBytes) switch self.state { @@ -2082,7 +2082,7 @@ final class TypedHTTPServerUpgradeTestCase: HTTPServerUpgradeTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) let stringRead = buf.readString(length: buf.readableBytes) switch self.state { diff --git a/Tests/NIOHTTP1Tests/HTTPTest.swift b/Tests/NIOHTTP1Tests/HTTPTest.swift index 62753d60e0..b1cf126e80 100644 --- a/Tests/NIOHTTP1Tests/HTTPTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPTest.swift @@ -29,7 +29,7 @@ private final class TestChannelInboundHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - context.fireChannelRead(self.wrapInboundOut(self.body(self.unwrapInboundIn(data)))) + context.fireChannelRead(Self.wrapInboundOut(self.body(Self.unwrapInboundIn(data)))) } } diff --git a/Tests/NIOHTTP1Tests/NIOHTTPObjectAggregatorTest.swift b/Tests/NIOHTTP1Tests/NIOHTTPObjectAggregatorTest.swift index 0f9015bb20..4931be76af 100644 --- a/Tests/NIOHTTP1Tests/NIOHTTPObjectAggregatorTest.swift +++ b/Tests/NIOHTTP1Tests/NIOHTTPObjectAggregatorTest.swift @@ -43,7 +43,7 @@ private final class ReadRecorder: ChannelInboundHandler, Removable public var reads: [Event] = [] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.reads.append(.channelRead(self.unwrapInboundIn(data))) + self.reads.append(.channelRead(Self.unwrapInboundIn(data))) context.fireChannelRead(data) } @@ -69,7 +69,7 @@ private final class WriteRecorder: ChannelOutboundHandler, RemovableChannelHandl public var writes: [HTTPServerResponsePart] = [] func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - self.writes.append(self.unwrapOutboundIn(data)) + self.writes.append(Self.unwrapOutboundIn(data)) context.write(data, promise: promise) } diff --git a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift index bd4d668d13..b1fc060feb 100644 --- a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift +++ b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift @@ -24,9 +24,9 @@ private final class IPHeaderRemoverHandler: ChannelInboundHandler { typealias InboundOut = AddressedEnvelope func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var data = self.unwrapInboundIn(data) + var data = Self.unwrapInboundIn(data) assert(data.data.readIPv4Header() != nil) - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) } } @@ -52,11 +52,11 @@ private final class LineDelimiterCoder: ByteToMessageDecoder, MessageToByteEncod buffer.moveReaderIndex(forwardBy: 1) if id == inboundID { - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) } return .continue } else { - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: readable)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: readable)!)) buffer.moveReaderIndex(forwardBy: 1) return .continue } @@ -110,7 +110,7 @@ private final class TLSUserEventHandler: ChannelInboundHandler, RemovableChannel } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) let string = String(buffer: buffer) if string.hasPrefix("negotiate-alpn:") { @@ -136,12 +136,12 @@ private final class ByteBufferToStringHandler: ChannelDuplexHandler { typealias OutboundOut = ByteBuffer func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) - context.fireChannelRead(self.wrapInboundOut(String(buffer: buffer))) + let buffer = Self.unwrapInboundIn(data) + context.fireChannelRead(Self.wrapInboundOut(String(buffer: buffer))) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let buffer = ByteBuffer(string: self.unwrapOutboundIn(data)) + let buffer = ByteBuffer(string: Self.unwrapOutboundIn(data)) context.write(.init(buffer), promise: promise) } } @@ -153,13 +153,13 @@ private final class ByteBufferToByteHandler: ChannelDuplexHandler { typealias OutboundOut = ByteBuffer func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) let byte = buffer.readInteger(as: UInt8.self)! - context.fireChannelRead(self.wrapInboundOut(byte)) + context.fireChannelRead(Self.wrapInboundOut(byte)) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let buffer = ByteBuffer(integer: self.unwrapOutboundIn(data)) + let buffer = ByteBuffer(integer: Self.unwrapOutboundIn(data)) context.write(.init(buffer), promise: promise) } } @@ -177,23 +177,23 @@ private final class AddressedEnvelopingHandler: ChannelDuplexHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let envelope = self.unwrapInboundIn(data) + let envelope = Self.unwrapInboundIn(data) self.remoteAddress = envelope.remoteAddress - context.fireChannelRead(self.wrapInboundOut(envelope.data)) + context.fireChannelRead(Self.wrapInboundOut(envelope.data)) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let buffer = self.unwrapOutboundIn(data) + let buffer = Self.unwrapOutboundIn(data) if let remoteAddress = self.remoteAddress { context.write( - self.wrapOutboundOut(AddressedEnvelope(remoteAddress: remoteAddress, data: buffer)), + Self.wrapOutboundOut(AddressedEnvelope(remoteAddress: remoteAddress, data: buffer)), promise: promise ) return } - context.write(self.wrapOutboundOut(buffer), promise: promise) + context.write(Self.wrapOutboundOut(buffer), promise: promise) } } @@ -489,7 +489,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let channel = self.unwrapInboundIn(data) + let channel = Self.unwrapInboundIn(data) self.channels.withLockedValue { $0.append(channel) } diff --git a/Tests/NIOPosixTests/BootstrapTest.swift b/Tests/NIOPosixTests/BootstrapTest.swift index 7d26eeb4e8..250db702cd 100644 --- a/Tests/NIOPosixTests/BootstrapTest.swift +++ b/Tests/NIOPosixTests/BootstrapTest.swift @@ -814,7 +814,7 @@ private final class WriteStringOnChannelActive: ChannelInboundHandler { func channelActive(context: ChannelHandlerContext) { var buffer = context.channel.allocator.buffer(capacity: self.string.utf8.count) buffer.writeString(string) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } } diff --git a/Tests/NIOPosixTests/ChannelPipelineTest.swift b/Tests/NIOPosixTests/ChannelPipelineTest.swift index 7fd0e2279d..fca47b0f9a 100644 --- a/Tests/NIOPosixTests/ChannelPipelineTest.swift +++ b/Tests/NIOPosixTests/ChannelPipelineTest.swift @@ -33,15 +33,15 @@ private final class IndexWritingHandler: ChannelDuplexHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) buf.writeInteger(UInt8(self.index)) - context.fireChannelRead(self.wrapInboundOut(buf)) + context.fireChannelRead(Self.wrapInboundOut(buf)) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - var buf = self.unwrapOutboundIn(data) + var buf = Self.unwrapOutboundIn(data) buf.writeInteger(UInt8(self.index)) - context.write(self.wrapOutboundOut(buf), promise: promise) + context.write(Self.wrapOutboundOut(buf), promise: promise) } } @@ -260,7 +260,7 @@ class ChannelPipelineTest: XCTestCase { public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { do { - context.write(self.wrapOutboundOut(try body(self.unwrapOutboundIn(data))), promise: promise) + context.write(Self.wrapOutboundOut(try body(Self.unwrapOutboundIn(data))), promise: promise) } catch let err { promise!.fail(err) } @@ -285,7 +285,7 @@ class ChannelPipelineTest: XCTestCase { typealias InboundOut = Int public func handlerRemoved(context: ChannelHandlerContext) { - context.fireChannelRead(self.wrapInboundOut(1)) + context.fireChannelRead(Self.wrapInboundOut(1)) } } @@ -347,8 +347,8 @@ class ChannelPipelineTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let data = self.unwrapInboundIn(data) - context.fireChannelRead(self.wrapInboundOut(data + [self.no])) + let data = Self.unwrapInboundIn(data) + context.fireChannelRead(Self.wrapInboundOut(data + [self.no])) } } @@ -364,8 +364,8 @@ class ChannelPipelineTest: XCTestCase { } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let data = self.unwrapOutboundIn(data) - context.write(self.wrapOutboundOut(data + [self.no]), promise: promise) + let data = Self.unwrapOutboundIn(data) + context.write(Self.wrapOutboundOut(data + [self.no]), promise: promise) } } @@ -376,9 +376,9 @@ class ChannelPipelineTest: XCTestCase { typealias OutboundOut = [Int] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let data = self.unwrapInboundIn(data) - context.writeAndFlush(self.wrapOutboundOut(data.map { $0 * -1 }), promise: nil) - context.fireChannelRead(self.wrapInboundOut(data)) + let data = Self.unwrapInboundIn(data) + context.writeAndFlush(Self.wrapOutboundOut(data.map { $0 * -1 }), promise: nil) + context.fireChannelRead(Self.wrapInboundOut(data)) } } @@ -388,10 +388,10 @@ class ChannelPipelineTest: XCTestCase { typealias OutboundOut = ByteBuffer func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let data = self.unwrapOutboundIn(data) + let data = Self.unwrapOutboundIn(data) var buf = context.channel.allocator.buffer(capacity: 123) buf.writeString(String(describing: data)) - context.write(self.wrapOutboundOut(buf), promise: promise) + context.write(Self.wrapOutboundOut(buf), promise: promise) } } @@ -524,7 +524,7 @@ class ChannelPipelineTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { if let dataString = data.tryAs(type: String.self) { - context.fireChannelRead(self.wrapInboundOut(dataString.count)) + context.fireChannelRead(Self.wrapInboundOut(dataString.count)) } } } @@ -535,7 +535,7 @@ class ChannelPipelineTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { if var buffer = data.tryAs(type: ByteBuffer.self) { - context.fireChannelRead(self.wrapInboundOut(buffer.readString(length: buffer.readableBytes)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readString(length: buffer.readableBytes)!)) } } } @@ -993,7 +993,7 @@ class ChannelPipelineTest: XCTestCase { typealias InboundOut = () func channelInactive(context: ChannelHandlerContext) { - context.fireChannelRead(self.wrapInboundOut(())) + context.fireChannelRead(Self.wrapInboundOut(())) } } let handler = FireWhenInactiveHandler() @@ -1258,12 +1258,12 @@ class ChannelPipelineTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let step = self.unwrapInboundIn(data) + let step = Self.unwrapInboundIn(data) self.state.next() XCTAssertEqual(self.state, step) // just to communicate to the outside where we are in our state machine - context.fireChannelRead(self.wrapInboundOut(self.state)) + context.fireChannelRead(Self.wrapInboundOut(self.state)) switch step { case .triggerEventRead: @@ -1298,7 +1298,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertEqual(.handlerRemovedCalled, self.state) // just to communicate to the outside where we are in our state machine - context.fireChannelRead(self.wrapInboundOut(self.state)) + context.fireChannelRead(Self.wrapInboundOut(self.state)) // Step 4: This happens when the pipeline is being torn down, so let's now also finish the manual // removal process. diff --git a/Tests/NIOPosixTests/ChannelTests.swift b/Tests/NIOPosixTests/ChannelTests.swift index b7928388f9..8b86e834a4 100644 --- a/Tests/NIOPosixTests/ChannelTests.swift +++ b/Tests/NIOPosixTests/ChannelTests.swift @@ -1900,7 +1900,7 @@ public final class ChannelTests: XCTestCase { if !self.expectingData { XCTFail("Received data before we expected it.") } else { - let data = self.unwrapInboundIn(data) + let data = Self.unwrapInboundIn(data) XCTAssertEqual(data.getString(at: data.readerIndex, length: data.readableBytes), "test") } } @@ -1962,7 +1962,7 @@ public final class ChannelTests: XCTestCase { ) } self.numberOfChannelReads += 1 - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) XCTAssertLessThanOrEqual(buffer.readableBytes, 8) XCTAssertEqual(1, self.numberOfChannelReads) context.close(mode: .all, promise: nil) @@ -2455,7 +2455,7 @@ public final class ChannelTests: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, self.state) self.state = .read - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) XCTAssertEqual(1, buffer.readableBytes) XCTAssertEqual([0xff], buffer.readBytes(length: 1)!) } @@ -2860,14 +2860,14 @@ public final class ChannelTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) XCTFail("unexpected read: \(String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))") } func channelActive(context: ChannelHandlerContext) { var buffer = context.channel.allocator.buffer(capacity: 1) buffer.writeStaticString("X") - context.channel.writeAndFlush(self.wrapOutboundOut(buffer)).map { context.channel }.cascade( + context.channel.writeAndFlush(Self.wrapOutboundOut(buffer)).map { context.channel }.cascade( to: self.channelAvailablePromise ) } @@ -2944,7 +2944,7 @@ public final class ChannelTests: XCTestCase { } workaroundSR487() - return context.writeAndFlush(self.wrapOutboundOut(buffer)) + return context.writeAndFlush(Self.wrapOutboundOut(buffer)) }.map { XCTFail("this should have failed") }.whenFailure { error in @@ -2960,7 +2960,7 @@ public final class ChannelTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) XCTAssertEqual("X", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self)) context.close(promise: nil) } @@ -3411,7 +3411,7 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler { // emitted. The flush for that write should result in the writability flipping back // again. let b1 = context.channel.allocator.buffer(repeating: 0, count: 50) - context.write(self.wrapOutboundOut(b1)).whenSuccess { _ in + context.write(Self.wrapOutboundOut(b1)).whenSuccess { _ in // We should still be writable. XCTAssertTrue(context.channel.isWritable) XCTAssertEqual(self.isNotWritableCount, 0) @@ -3420,7 +3420,7 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler { // Write again. But now breach high water mark. This should cause us to become // unwritable. let b2 = context.channel.allocator.buffer(repeating: 0, count: 250) - context.write(self.wrapOutboundOut(b2), promise: nil) + context.write(Self.wrapOutboundOut(b2), promise: nil) XCTAssertFalse(context.channel.isWritable) XCTAssertEqual(self.isNotWritableCount, 1) XCTAssertEqual(self.isWritableCount, 0) @@ -3430,7 +3430,7 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler { } // Queue another write and flush. - context.writeAndFlush(self.wrapOutboundOut(b1), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(b1), promise: nil) } func channelWritabilityChanged(context: ChannelHandlerContext) { diff --git a/Tests/NIOPosixTests/CodecTest.swift b/Tests/NIOPosixTests/CodecTest.swift index 46782f0766..5b60900820 100644 --- a/Tests/NIOPosixTests/CodecTest.swift +++ b/Tests/NIOPosixTests/CodecTest.swift @@ -65,7 +65,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { guard buffer.readableBytes >= MemoryLayout.size else { return .needMoreData } - context.fireChannelRead(self.wrapInboundOut(buffer.readInteger()!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readInteger()!)) return .continue } @@ -100,7 +100,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { return .needMoreData } - context.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(Self.wrapInboundOut(buffer)) return .continue } @@ -122,7 +122,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { return .needMoreData } - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 2048)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 2048)!)) return .continue } @@ -385,13 +385,13 @@ public final class ByteToMessageDecoderTest: XCTestCase { self.hasReentranced = true reentrantWriteBuffer.clear() reentrantWriteBuffer.writeStaticString("3") - context.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) + context.channel.pipeline.fireChannelRead(Self.wrapInboundOut(reentrantWriteBuffer)) } - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 1)!)) if self.numberOfDecodeCalls == 2 { reentrantWriteBuffer.clear() reentrantWriteBuffer.writeStaticString("4") - context.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) + context.channel.pipeline.fireChannelRead(Self.wrapInboundOut(reentrantWriteBuffer)) } return .continue } @@ -459,7 +459,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { let originalBuffer = buffer - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: buffer.readableBytes)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: buffer.readableBytes)!)) if originalBuffer.readableBytesView.last == "0".utf8.last { context.close().whenFailure { error in XCTFail("unexpected error: \(error)") @@ -687,7 +687,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { defer { self.state += 1 } - context.fireChannelRead(self.wrapInboundOut(self.state)) + context.fireChannelRead(Self.wrapInboundOut(self.state)) return .continue } else { return .needMoreData @@ -700,7 +700,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { seenEOF: Bool ) throws -> DecodingState { XCTAssertTrue(seenEOF) - context.fireChannelRead(self.wrapInboundOut(buffer.readableBytes * -1)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readableBytes * -1)) return .needMoreData } } @@ -745,7 +745,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { ) } context.fireChannelRead( - self.wrapInboundOut(String(decoding: slice.readableBytesView, as: Unicode.UTF8.self)) + Self.wrapInboundOut(String(decoding: slice.readableBytesView, as: Unicode.UTF8.self)) ) return .continue } else { @@ -783,7 +783,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 16) { - context.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(Self.wrapInboundOut(slice)) context.channel.close().whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -799,7 +799,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { seenEOF: Bool ) throws -> DecodingState { XCTAssertTrue(seenEOF) - context.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(Self.wrapInboundOut(buffer)) return .needMoreData } } @@ -833,7 +833,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 16) { - context.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(Self.wrapInboundOut(slice)) context.pipeline.removeHandler(context: context).whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -849,7 +849,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { seenEOF: Bool ) throws -> DecodingState { XCTAssertFalse(seenEOF) - context.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(Self.wrapInboundOut(buffer)) return .needMoreData } } @@ -880,7 +880,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 16) { - context.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(Self.wrapInboundOut(slice)) context.close().whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -936,7 +936,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { self.callsToDecode += 1 XCTAssertEqual(1, self.callsToDecode) context.fireChannelRead( - self.wrapInboundOut( + Self.wrapInboundOut( String( decoding: buffer.readBytes(length: 1)!, as: Unicode.UTF8.self @@ -958,7 +958,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { self.callsToDecodeLast += 1 XCTAssertLessThanOrEqual(self.callsToDecodeLast, 2) context.fireChannelRead( - self.wrapInboundOut( + Self.wrapInboundOut( String( decoding: buffer.readBytes(length: 4) ?? [ // "no bytes" 0x6e, 0x6f, 0x20, @@ -1011,7 +1011,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { self.decodeLastCalls += 1 XCTAssertEqual(1, self.decodeLastCalls) XCTAssertEqual(0, buffer.readableBytes) - context.fireChannelRead(self.wrapInboundOut(())) + context.fireChannelRead(Self.wrapInboundOut(())) return .needMoreData } } @@ -1048,7 +1048,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { self.decodeLastCalls += 1 XCTAssertEqual(1, self.decodeLastCalls) XCTAssertEqual(0, buffer.readableBytes) - context.fireChannelRead(self.wrapInboundOut(())) + context.fireChannelRead(Self.wrapInboundOut(())) return .needMoreData } } @@ -1188,7 +1188,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let string = buffer.readString(length: 1) { - context.fireChannelRead(self.wrapInboundOut(string)) + context.fireChannelRead(Self.wrapInboundOut(string)) return .continue } else { return .needMoreData @@ -1239,7 +1239,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.decodeRun += 1 if let string = buffer.readString(length: 1) { - context.fireChannelRead(self.wrapInboundOut("I: \(self.decodeRun): \(string)")) + context.fireChannelRead(Self.wrapInboundOut("I: \(self.decodeRun): \(string)")) XCTAssertNoThrow( try (context.channel as! EmbeddedChannel).writeOutbound("O: \(self.decodeRun): \(string)") ) @@ -1275,8 +1275,8 @@ public final class ByteToMessageDecoderTest: XCTestCase { } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let string = self.unwrapOutboundIn(data) - context.write(self.wrapOutboundOut("\(string) @ \(decoder.decodeRun)"), promise: promise) + let string = Self.unwrapOutboundIn(data) + context.write(Self.wrapOutboundOut("\(string) @ \(decoder.decodeRun)"), promise: promise) } } @@ -1473,7 +1473,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.decodeCalls += 1 XCTAssert(buffer.readableBytes > 0) - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 1)!)) if self.decodeCalls == 3 { context.close(promise: nil) } @@ -1528,7 +1528,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.decodeCalls += 1 XCTAssert(buffer.readableBytes > 0) - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 1)!)) if self.decodeCalls == 3 { context.channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed) } @@ -1966,7 +1966,7 @@ private class PairOfBytesDecoder: ByteToMessageDecoder { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 2) { - context.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(Self.wrapInboundOut(slice)) return .continue } else { return .needMoreData diff --git a/Tests/NIOPosixTests/DatagramChannelTests.swift b/Tests/NIOPosixTests/DatagramChannelTests.swift index 9703213b3b..40e0b3dcd0 100644 --- a/Tests/NIOPosixTests/DatagramChannelTests.swift +++ b/Tests/NIOPosixTests/DatagramChannelTests.swift @@ -85,14 +85,14 @@ final class DatagramReadRecorder: ChannelInboundHandler { func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, self.state) - let data = self.unwrapInboundIn(data) + let data = Self.unwrapInboundIn(data) reads.append(data) if let promise = readWaiters.removeValue(forKey: reads.count) { promise.succeed(reads) } - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) } func channelReadComplete(context: ChannelHandlerContext) { @@ -394,7 +394,7 @@ class DatagramChannelTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - XCTFail("Should not receive data but got \(self.unwrapInboundIn(data))") + XCTFail("Should not receive data but got \(Self.unwrapInboundIn(data))") } func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -480,7 +480,7 @@ class DatagramChannelTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - XCTFail("Should not receive data but got \(self.unwrapInboundIn(data))") + XCTFail("Should not receive data but got \(Self.unwrapInboundIn(data))") } func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -860,9 +860,9 @@ class DatagramChannelTests: XCTestCase { typealias OutboundOut = AddressedEnvelope func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let buffer = self.unwrapOutboundIn(data) + let buffer = Self.unwrapOutboundIn(data) context.write( - self.wrapOutboundOut(AddressedEnvelope(remoteAddress: context.channel.localAddress!, data: buffer)), + Self.wrapOutboundOut(AddressedEnvelope(remoteAddress: context.channel.localAddress!, data: buffer)), promise: promise ) } @@ -1064,11 +1064,11 @@ class DatagramChannelTests: XCTestCase { data: buffer ) - context.writeAndFlush(self.wrapOutboundOut(envelope)).cascadeFailure(to: self.completePromise) + context.writeAndFlush(Self.wrapOutboundOut(envelope)).cascadeFailure(to: self.completePromise) } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let envelope = self.unwrapInboundIn(data) + let envelope = Self.unwrapInboundIn(data) // Complete with the payload. self.completePromise.succeed(envelope.data) diff --git a/Tests/NIOPosixTests/EventLoopTest.swift b/Tests/NIOPosixTests/EventLoopTest.swift index 71b72f7f28..554de2e93b 100644 --- a/Tests/NIOPosixTests/EventLoopTest.swift +++ b/Tests/NIOPosixTests/EventLoopTest.swift @@ -1440,7 +1440,7 @@ public final class EventLoopTest: XCTestCase { self.readCalls += 1 XCTAssertEqual(1, self.readCalls) - var data = self.unwrapInboundIn(data) + var data = Self.unwrapInboundIn(data) XCTAssertEqual(1, data.readableBytes) XCTAssertNil(self.received) diff --git a/Tests/NIOPosixTests/IdleStateHandlerTest.swift b/Tests/NIOPosixTests/IdleStateHandlerTest.swift index 224258186d..9896300800 100644 --- a/Tests/NIOPosixTests/IdleStateHandlerTest.swift +++ b/Tests/NIOPosixTests/IdleStateHandlerTest.swift @@ -76,7 +76,7 @@ class IdleStateHandlerTest: XCTestCase { if writeToChannel { var buffer = context.channel.allocator.buffer(capacity: 4) buffer.writeStaticString("test") - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } } } diff --git a/Tests/NIOPosixTests/MulticastTest.swift b/Tests/NIOPosixTests/MulticastTest.swift index 9af3c973be..9ef566f82b 100644 --- a/Tests/NIOPosixTests/MulticastTest.swift +++ b/Tests/NIOPosixTests/MulticastTest.swift @@ -26,7 +26,7 @@ final class PromiseOnReadHandler: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.promise.succeed(self.unwrapInboundIn(data)) + self.promise.succeed(Self.unwrapInboundIn(data)) _ = context.pipeline.removeHandler(context: context) } } diff --git a/Tests/NIOPosixTests/SALChannelTests.swift b/Tests/NIOPosixTests/SALChannelTests.swift index 87dcd0f990..d4d5e45f5c 100644 --- a/Tests/NIOPosixTests/SALChannelTests.swift +++ b/Tests/NIOPosixTests/SALChannelTests.swift @@ -116,7 +116,7 @@ final class SALChannelTest: XCTestCase, SALTest { ordering: .relaxed ).exchanged ) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) case 3: // Next, we should go to false because we never send all the bytes. XCTAssertFalse(context.channel.isWritable) @@ -254,7 +254,7 @@ final class SALChannelTest: XCTestCase, SALTest { self.numberOfCalls += 1 XCTAssertEqual( "hello", - String(decoding: self.unwrapInboundIn(data).readableBytesView, as: Unicode.UTF8.self) + String(decoding: Self.unwrapInboundIn(data).readableBytesView, as: Unicode.UTF8.self) ) if self.numberOfCalls == 1 { self.group.leave() diff --git a/Tests/NIOPosixTests/SelectorTest.swift b/Tests/NIOPosixTests/SelectorTest.swift index 8d9d417915..3b392cb5c1 100644 --- a/Tests/NIOPosixTests/SelectorTest.swift +++ b/Tests/NIOPosixTests/SelectorTest.swift @@ -185,7 +185,7 @@ class SelectorTest: XCTestCase { XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value) XCTAssertFalse(self.didRead) - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) XCTAssertEqual("H", buf.readString(length: 1)!) self.didRead = true diff --git a/Tests/NIOPosixTests/SocketChannelTest.swift b/Tests/NIOPosixTests/SocketChannelTest.swift index f63ad55da4..80133abbdd 100644 --- a/Tests/NIOPosixTests/SocketChannelTest.swift +++ b/Tests/NIOPosixTests/SocketChannelTest.swift @@ -143,7 +143,7 @@ public final class SocketChannelTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - XCTFail("Should not accept a Channel but got \(self.unwrapInboundIn(data))") + XCTFail("Should not accept a Channel but got \(Self.unwrapInboundIn(data))") } func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -773,7 +773,7 @@ public final class SocketChannelTest: XCTestCase { typealias InboundIn = Channel func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.unwrapInboundIn(data).close(promise: nil) + Self.unwrapInboundIn(data).close(promise: nil) } func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -995,7 +995,7 @@ public final class SocketChannelTest: XCTestCase { func channelActive(context: ChannelHandlerContext) { var buffer = context.channel.allocator.buffer(capacity: 128) buffer.writeString(String(repeating: "x", count: 517)) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } func channelInactive(context: ChannelHandlerContext) { @@ -1131,7 +1131,7 @@ class DropAllReadsOnTheFloorHandler: ChannelDuplexHandler { // the connection is fully closed but because we support half-closure, we need to write to 'learn' that the // other side has actually fully closed the socket. func writeUntilError() { - context.writeAndFlush(self.wrapOutboundOut(buffer)).map { + context.writeAndFlush(Self.wrapOutboundOut(buffer)).map { writeUntilError() }.whenFailure { (_: Error) in self.waitUntilWriteFailedPromise.succeed(()) diff --git a/Tests/NIOPosixTests/StreamChannelsTest.swift b/Tests/NIOPosixTests/StreamChannelsTest.swift index 197e1c2b02..b9727f9633 100644 --- a/Tests/NIOPosixTests/StreamChannelsTest.swift +++ b/Tests/NIOPosixTests/StreamChannelsTest.swift @@ -159,11 +159,11 @@ class StreamChannelTest: XCTestCase { var buffer = context.channel.allocator.buffer(capacity: chunkSize) buffer.writeBytes(repeatElement(UInt8(ascii: "x"), count: chunkSize)) for _ in 0..<(totalAmount / chunkSize) { - context.write(self.wrapOutboundOut(buffer)).whenFailure { error in + context.write(Self.wrapOutboundOut(buffer)).whenFailure { error in XCTFail("unexpected error \(error)") } } - context.write(self.wrapOutboundOut(buffer)).map { + context.write(Self.wrapOutboundOut(buffer)).map { XCTAssertEqual(self.state, .thenTrueAgain) }.recover { error in XCTFail("unexpected error \(error)") @@ -339,7 +339,7 @@ class StreamChannelTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { guard self.areReadsOkayNow.load(ordering: .relaxed) else { - XCTFail("unexpected read of \(self.unwrapInboundIn(data))") + XCTFail("unexpected read of \(Self.unwrapInboundIn(data))") return } } @@ -433,7 +433,7 @@ class StreamChannelTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { // The two writes could be coalesced, so we add up the bytes and not always the number of read calls. - self.numberOfBytes += self.unwrapInboundIn(data).readableBytes + self.numberOfBytes += Self.unwrapInboundIn(data).readableBytes if self.numberOfBytes == 2 { self.allDonePromise.succeed(()) } @@ -488,7 +488,7 @@ class StreamChannelTest: XCTestCase { buffer.writeString("hello") context.channel.setOption(ChannelOptions.writeBufferWaterMark, value: .init(low: 1024, high: 1024)) .flatMap { - context.writeAndFlush(self.wrapOutboundOut(buffer)) + context.writeAndFlush(Self.wrapOutboundOut(buffer)) }.whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -512,7 +512,7 @@ class StreamChannelTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { // The two writes could be coalesced, so we add up the bytes and not always the number of read calls. - self.numberOfReads += self.unwrapInboundIn(data).readableBytes + self.numberOfReads += Self.unwrapInboundIn(data).readableBytes if self.numberOfReads >= self.expectedNumberOfBytes { self.allDonePromise.succeed(()) } @@ -653,7 +653,7 @@ class StreamChannelTest: XCTestCase { func writeOneMore() { self.bytesWritten += buffer.readableBytes - context.writeAndFlush(self.wrapOutboundOut(buffer)).whenFailure { error in + context.writeAndFlush(Self.wrapOutboundOut(buffer)).whenFailure { error in XCTFail("unexpected error \(error)") } context.eventLoop.scheduleTask(in: .microseconds(100)) { @@ -667,7 +667,7 @@ class StreamChannelTest: XCTestCase { buffer.writeString("1") self.state = .done self.bytesWritten += 1 - context.writeAndFlush(self.wrapOutboundOut(buffer)).whenFailure { error in + context.writeAndFlush(Self.wrapOutboundOut(buffer)).whenFailure { error in XCTFail("unexpected error \(error)") } self.wroteEnoughToBeStuckPromise.succeed(self.bytesWritten) @@ -733,7 +733,7 @@ class StreamChannelTest: XCTestCase { self.state = .done var buffer = context.channel.allocator.buffer(capacity: 10 * 1024 * 1024) buffer.writeBytes(Array(repeating: UInt8(ascii: "X"), count: buffer.capacity - 1)) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: self.finishedBigWritePromise) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: self.finishedBigWritePromise) self.beganBigWritePromise.succeed(()) case .done: () // ignored @@ -764,7 +764,7 @@ class StreamChannelTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) switch self.state { case .waitingForInitialOutsideReadCall: XCTFail("unexpected \(#function)") @@ -906,7 +906,7 @@ class StreamChannelTest: XCTestCase { // Let's send another 2 bytes, ... var buffer = context.channel.allocator.buffer(capacity: amount) buffer.writeBytes(Array(repeating: UInt8(ascii: "X"), count: amount)) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) // ... and let's close context.close(promise: nil) @@ -952,7 +952,7 @@ final class AccumulateAllReads: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) let closeAfter = buffer.readableBytesView.last == UInt8(ascii: "$") self.accumulator.writeBuffer(&buffer) if closeAfter { diff --git a/Tests/NIOPosixTests/TestUtils.swift b/Tests/NIOPosixTests/TestUtils.swift index 8c44fed395..df571c2f46 100644 --- a/Tests/NIOPosixTests/TestUtils.swift +++ b/Tests/NIOPosixTests/TestUtils.swift @@ -294,7 +294,7 @@ final class ByteCountingHandler: ChannelInboundHandler, RemovableChannelHandler } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var currentBuffer = self.unwrapInboundIn(data) + var currentBuffer = Self.unwrapInboundIn(data) buffer.writeBuffer(¤tBuffer) if buffer.readableBytes == numBytes { diff --git a/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift b/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift index 253075a056..59e9ff2b3a 100644 --- a/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift +++ b/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift @@ -64,7 +64,7 @@ class UniversalBootstrapSupportTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let channel = self.unwrapInboundIn(data) + let channel = Self.unwrapInboundIn(data) self.acceptedChannels.append(channel) if self.acceptedChannels.count == 1 { self.firstArrived.succeed(()) diff --git a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift index 5f39f09246..498a6f9761 100644 --- a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift +++ b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift @@ -45,7 +45,7 @@ final class DuplicatingReadHandler: ChannelInboundHandler { func channelRead(context: ChannelHandlerContext, data: NIOAny) { if !self.hasDuplicatedRead { self.hasDuplicatedRead = true - try! self.channel.writeInbound(self.unwrapInboundIn(data)) + try! self.channel.writeInbound(Self.unwrapInboundIn(data)) } context.fireChannelRead(data) } diff --git a/Tests/NIOTestUtilsTests/ByteToMessageDecoderVerifierTest.swift b/Tests/NIOTestUtilsTests/ByteToMessageDecoderVerifierTest.swift index 4e1ebd5804..d6ab6a6d00 100644 --- a/Tests/NIOTestUtilsTests/ByteToMessageDecoderVerifierTest.swift +++ b/Tests/NIOTestUtilsTests/ByteToMessageDecoderVerifierTest.swift @@ -27,7 +27,7 @@ class ByteToMessageDecoderVerifierTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { buffer.moveReaderIndex(to: buffer.writerIndex) - context.fireChannelRead(self.wrapInboundOut("Y")) + context.fireChannelRead(Self.wrapInboundOut("Y")) return .needMoreData } @@ -110,7 +110,7 @@ class ByteToMessageDecoderVerifierTest: XCTestCase { typealias InboundOut = String func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { - context.fireChannelRead(self.wrapInboundOut("Y")) + context.fireChannelRead(Self.wrapInboundOut("Y")) return .needMoreData } @@ -160,7 +160,7 @@ class ByteToMessageDecoderVerifierTest: XCTestCase { ) throws -> DecodingState { while try self.decode(context: context, buffer: &buffer) == .continue {} if buffer.readableBytes > 0 { - context.fireChannelRead(self.wrapInboundOut("leftover")) + context.fireChannelRead(Self.wrapInboundOut("leftover")) } return .needMoreData } diff --git a/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift b/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift index c1dd109644..293fb624bc 100644 --- a/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift +++ b/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift @@ -433,7 +433,7 @@ private final class TestHTTPHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head(let responseHead): guard case .ok = responseHead.status else { self.responsePromise.fail(ResponseError.badStatus) @@ -496,14 +496,14 @@ private final class AggregateBodyHandler: ChannelInboundHandler { var receivedSoFar: ByteBuffer? = nil func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head: context.fireChannelRead(data) case .body(var buffer): self.receivedSoFar.setOrWriteBuffer(&buffer) case .end: if let receivedSoFar = self.receivedSoFar { - context.fireChannelRead(self.wrapInboundOut(.body(receivedSoFar))) + context.fireChannelRead(Self.wrapInboundOut(.body(receivedSoFar))) } context.fireChannelRead(data) } diff --git a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift index ac0a1363cc..23202c2c4b 100644 --- a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift @@ -125,13 +125,13 @@ extension ChannelInboundHandler where OutboundOut == HTTPClientRequestPart { headers: headers ) - context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) + context.write(Self.wrapOutboundOut(.head(requestHead)), promise: nil) let emptyBuffer = context.channel.allocator.buffer(capacity: 0) let body = HTTPClientRequestPart.body(.byteBuffer(emptyBuffer)) - context.write(self.wrapOutboundOut(body), promise: nil) + context.write(Self.wrapOutboundOut(body), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } } @@ -145,7 +145,7 @@ private class WebSocketRecorderHandler: ChannelInboundHandler, ChannelOutboundHa public var errors: [Error] = [] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = self.unwrapInboundIn(data) + let frame = Self.unwrapInboundIn(data) self.frames.append(frame) } diff --git a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift index e4402e7326..8a0a7f1944 100644 --- a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift +++ b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift @@ -43,7 +43,7 @@ private final class SynchronousCloser: ChannelInboundHandler { private var closeFrame: WebSocketFrame? func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = self.unwrapInboundIn(data) + let frame = Self.unwrapInboundIn(data) guard case .connectionClose = frame.opcode else { context.fireChannelRead(data) return diff --git a/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift index c1edc2c1a1..39161af5c7 100644 --- a/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift @@ -105,7 +105,7 @@ private class WebSocketRecorderHandler: ChannelInboundHandler { fileprivate var errors: [Error] = [] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = self.unwrapInboundIn(data) + let frame = Self.unwrapInboundIn(data) self.frames.append(frame) }