From 0bbed6d72f71ce0fe2efed6fe5eaa76b8294bb80 Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Thu, 1 Mar 2018 22:40:52 -0800 Subject: [PATCH] * removed trailing whitespace (#52) --- Sources/NIO/BaseSocket.swift | 24 ++--- Sources/NIO/BlockingIOThreadPool.swift | 24 ++--- Sources/NIO/Bootstrap.swift | 42 ++++---- Sources/NIO/ByteBuffer-core.swift | 12 +-- Sources/NIO/Channel.swift | 54 +++++------ Sources/NIO/ChannelHandler.swift | 72 +++++++------- Sources/NIO/ChannelHandlers.swift | 52 +++++----- Sources/NIO/ChannelInvoker.swift | 64 ++++++------- Sources/NIO/ChannelOption.swift | 38 ++++---- Sources/NIO/ChannelPipeline.swift | 4 +- Sources/NIO/CircularBuffer.swift | 26 ++--- Sources/NIO/Codec.swift | 36 +++---- Sources/NIO/Embedded.swift | 44 ++++----- Sources/NIO/EventLoop.swift | 96 +++++++++---------- Sources/NIO/EventLoopFuture.swift | 36 +++---- Sources/NIO/FileDescriptor.swift | 6 +- Sources/NIO/FileHandle.swift | 4 +- Sources/NIO/FileRegion.swift | 12 +-- Sources/NIO/IO.swift | 6 +- Sources/NIO/LinuxCPUSet.swift | 26 ++--- Sources/NIO/NIOAny.swift | 22 ++--- Sources/NIO/RecvByteBufferAllocator.swift | 40 ++++---- Sources/NIO/Resolver.swift | 4 +- Sources/NIO/Selector.swift | 54 +++++------ Sources/NIO/ServerSocket.swift | 10 +- Sources/NIO/Socket.swift | 18 ++-- Sources/NIO/SocketAddresses.swift | 10 +- Sources/NIO/SocketChannel.swift | 2 +- Sources/NIO/System.swift | 34 +++---- Sources/NIO/Thread.swift | 24 ++--- Sources/NIO/TypeAssistedChannelHandler.swift | 6 +- Sources/NIOChatClient/main.swift | 2 +- Sources/NIOChatServer/main.swift | 26 ++--- Sources/NIOEchoClient/main.swift | 8 +- Sources/NIOHTTP1/HTTPDecoder.swift | 38 ++++---- Sources/NIOHTTP1/HTTPEncoder.swift | 22 ++--- Sources/NIOHTTP1/HTTPResponseCompressor.swift | 2 +- Sources/NIOHTTP1/HTTPTypes.swift | 4 +- Sources/NIOPriorityQueue/Heap.swift | 30 +++--- Sources/NIOPriorityQueue/PriorityQueue.swift | 12 +-- Tests/LinuxMain.swift | 2 +- .../HTTPRequestEncoderTest.swift | 26 ++--- .../NIOHTTP1Tests/HTTPServerClientTest.swift | 82 ++++++++-------- Tests/NIOPriorityQueueTests/HeapTests.swift | 2 +- Tests/NIOTests/BaseObjectsTest.swift | 14 +-- Tests/NIOTests/BlockingIOThreadPoolTest.swift | 4 +- Tests/NIOTests/ByteBufferTest.swift | 90 ++++++++--------- Tests/NIOTests/ChannelPipelineTest.swift | 42 ++++---- Tests/NIOTests/ChannelTests.swift | 76 +++++++-------- Tests/NIOTests/CircularBufferTests.swift | 22 ++--- Tests/NIOTests/CodecTest.swift | 40 ++++---- Tests/NIOTests/EchoServerClientTest.swift | 74 +++++++------- Tests/NIOTests/EmbeddedChannelTest.swift | 20 ++-- Tests/NIOTests/EventLoopTest.swift | 24 ++--- Tests/NIOTests/FileRegionTest.swift | 12 +-- Tests/NIOTests/IdleStateHandlerTest.swift | 26 ++--- Tests/NIOTests/RecvByteBufAllocatorTest.swift | 10 +- Tests/NIOTests/SocketChannelTest.swift | 2 +- Tests/NIOTests/SystemCallWrapperHelpers.swift | 14 +-- Tests/NIOTests/TestUtils.swift | 12 +-- .../TypeAssistedChannelHandlerTests.swift | 2 +- 61 files changed, 821 insertions(+), 821 deletions(-) diff --git a/Sources/NIO/BaseSocket.swift b/Sources/NIO/BaseSocket.swift index 0c8501ce0..642e66aa7 100644 --- a/Sources/NIO/BaseSocket.swift +++ b/Sources/NIO/BaseSocket.swift @@ -183,14 +183,14 @@ class BaseSocket: Selectable { private let descriptor: CInt public private(set) var isOpen: Bool - + func withUnsafeFileDescriptor(_ body: (CInt) throws -> T) throws -> T { guard self.isOpen else { throw IOError(errnoCode: EBADF, reason: "file descriptor already closed!") } return try body(descriptor) } - + /// Returns the local bound `SocketAddress` of the socket. /// /// - returns: The local bound address. @@ -198,7 +198,7 @@ class BaseSocket: Selectable { final func localAddress() throws -> SocketAddress { return try get_addr { try Posix.getsockname(socket: $0, address: $1, addressLength: $2) } } - + /// Returns the connected `SocketAddress` of the socket. /// /// - returns: The connected address. @@ -213,7 +213,7 @@ class BaseSocket: Selectable { try addr.withMutableSockAddr { addressPtr, size in var size = socklen_t(size) - + try withUnsafeFileDescriptor { fd in try body(fd, addressPtr, &size) } @@ -232,7 +232,7 @@ class BaseSocket: Selectable { let sock = try Posix.socket(domain: protocolFamily, type: type, protocol: 0) - + if protocolFamily == AF_INET6 { var zero: Int32 = 0 do { @@ -267,7 +267,7 @@ class BaseSocket: Selectable { deinit { assert(!self.isOpen, "leak of open BaseSocket") } - + /// Set the socket as non-blocking. /// /// All I/O operations will not block and so may return before the actual action could be completed. @@ -278,7 +278,7 @@ class BaseSocket: Selectable { try Posix.fcntl(descriptor: fd, command: F_SETFL, value: O_NONBLOCK) } } - + /// Set the given socket option. /// /// This basically just delegates to `setsockopt` syscall. @@ -291,7 +291,7 @@ class BaseSocket: Selectable { final func setOption(level: Int32, name: Int32, value: T) throws { try withUnsafeFileDescriptor { fd in var val = value - + _ = try Posix.setsockopt( socket: fd, level: level, @@ -317,12 +317,12 @@ class BaseSocket: Selectable { val.deinitialize(count: 1) val.deallocate() } - + try Posix.getsockopt(socket: fd, level: level, optionName: name, optionValue: val, optionLen: &length) return val.pointee } } - + /// Bind the socket to the given `SocketAddress`. /// /// - parameters: @@ -333,7 +333,7 @@ class BaseSocket: Selectable { func doBind(ptr: UnsafePointer, bytes: Int) throws { try Posix.bind(descriptor: fd, ptr: ptr, bytes: bytes) } - + switch address { case .v4(let address): var addr = address.address @@ -347,7 +347,7 @@ class BaseSocket: Selectable { } } } - + /// Close the socket. /// /// After the socket was closed all other methods will throw an `IOError` when called. diff --git a/Sources/NIO/BlockingIOThreadPool.swift b/Sources/NIO/BlockingIOThreadPool.swift index 0c9937a73..cfc6e1386 100644 --- a/Sources/NIO/BlockingIOThreadPool.swift +++ b/Sources/NIO/BlockingIOThreadPool.swift @@ -18,7 +18,7 @@ import NIOConcurrencyHelpers /// A thread pool that should be used for blocking IO. public final class BlockingIOThreadPool { - + /// The state of the `WorkItem`. public enum WorkItemState { /// The `WorkItem` is active now and in process by the `BlockingIOThreadPool`. @@ -26,10 +26,10 @@ public final class BlockingIOThreadPool { /// The `WorkItem` was cancelled and will not be processed by the `BlockingIOThreadPool`. case cancelled } - + /// The work that should be done by the `BlockingIOThreadPool`. public typealias WorkItem = (WorkItemState) -> Void - + private enum State { /// The `BlockingIOThreadPool` is already stopped. case stopped @@ -43,7 +43,7 @@ public final class BlockingIOThreadPool { private let queues: [DispatchQueue] private var state: State = .stopped private let numberOfThreads: Int - + /// Gracefully shutdown this `BlockingIOThreadPool`. All tasks will be run before shutdown will take place. /// /// - parameters: @@ -62,17 +62,17 @@ public final class BlockingIOThreadPool { case .shuttingDown, .stopped: () } - + self.queues.forEach { q in q.async(group: g) {} } - + g.notify(queue: queue) { callback(nil) } } } - + /// Submit a `WorkItem` to process. /// /// - parameters: @@ -92,7 +92,7 @@ public final class BlockingIOThreadPool { /* if item couldn't be added run it immediately indicating that it couldn't be run */ item.map { $0(.cancelled) } } - + /// Initialize a `BlockingIOThreadPool` thread pool with `numberOfThreads` threads. /// /// - parameters: @@ -103,13 +103,13 @@ public final class BlockingIOThreadPool { DispatchQueue(label: "BlockingIOThreadPool thread #\($0)") } } - + private func process(identifier: Int) { var item: WorkItem? = nil repeat { /* wait until work has become available */ self.semaphore.wait() - + item = self.lock.withLock { () -> (WorkItem)? in switch self.state { case .running(var items): @@ -129,7 +129,7 @@ public final class BlockingIOThreadPool { item.map { $0(.active) } } while item != nil } - + /// Start the `NonBlockingIOThreadPool` if not already started. public func start() { self.lock.withLock { @@ -157,7 +157,7 @@ extension BlockingIOThreadPool { public func shutdownGracefully(_ callback: @escaping (Error?) -> Void) { self.shutdownGracefully(queue: .global(), callback) } - + public func syncShutdownGracefully() throws { let errorStorageLock = Lock() var errorStorage: Swift.Error? = nil diff --git a/Sources/NIO/Bootstrap.swift b/Sources/NIO/Bootstrap.swift index fd876322b..8192ab4be 100644 --- a/Sources/NIO/Bootstrap.swift +++ b/Sources/NIO/Bootstrap.swift @@ -46,7 +46,7 @@ /// ``` /// public final class ServerBootstrap { - + private let group: EventLoopGroup private let childGroup: EventLoopGroup private var serverChannelInit: ((Channel) -> EventLoopFuture<()>)? @@ -71,7 +71,7 @@ public final class ServerBootstrap { self.group = group self.childGroup = childGroup } - + /// Initialize the `ServerSocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// @@ -83,7 +83,7 @@ public final class ServerBootstrap { self.serverChannelInit = initializer return self } - + /// Initialize the accepted `SocketChannel`s with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// @@ -93,7 +93,7 @@ public final class ServerBootstrap { self.childChannelInit = initializer return self } - + /// Specifies a `ChannelOption` to be applied to the `ServerSocketChannel`. /// /// - note: To specify options for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelOption`. @@ -105,7 +105,7 @@ public final class ServerBootstrap { serverChannelOptions.put(key: option, value: value) return self } - + /// Specifies a `ChannelOption` to be applied to the accepted `SocketChannel`s. /// /// - parameters: @@ -115,7 +115,7 @@ public final class ServerBootstrap { childChannelOptions.put(key: option, value: value) return self } - + /// Bind the `ServerSocketChannel` to `host` and `port`. /// /// - parameters: @@ -160,13 +160,13 @@ public final class ServerBootstrap { let serverChannelInit = self.serverChannelInit ?? { _ in eventLoop.newSucceededFuture(result: ()) } let childChannelInit = self.childChannelInit let childChannelOptions = self.childChannelOptions - + let promise: EventLoopPromise = eventLoop.newPromise() do { let serverChannel = try ServerSocketChannel(eventLoop: eventLoop as! SelectableEventLoop, group: childEventLoopGroup, protocolFamily: address.protocolFamily) - + serverChannelInit(serverChannel).then { serverChannel.pipeline.add(handler: AcceptHandler(childChannelInitializer: childChannelInit, childChannelOptions: childChannelOptions)) @@ -185,18 +185,18 @@ public final class ServerBootstrap { return promise.futureResult } - + private class AcceptHandler: ChannelInboundHandler { public typealias InboundIn = SocketChannel - + private let childChannelInit: ((Channel) -> EventLoopFuture<()>)? private let childChannelOptions: ChannelOptionStorage - + init(childChannelInitializer: ((Channel) -> EventLoopFuture<()>)?, childChannelOptions: ChannelOptionStorage) { self.childChannelInit = childChannelInitializer self.childChannelOptions = childChannelOptions } - + func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { let accepted = self.unwrapInboundIn(data) let hopEventLoopPromise: EventLoopPromise<()> = ctx.eventLoop.newPromise() @@ -214,7 +214,7 @@ public final class ServerBootstrap { self.closeAndFire(ctx: ctx, accepted: accepted, err: error) } } - + private func closeAndFire(ctx: ChannelHandlerContext, accepted: SocketChannel, err: Error) { _ = accepted.close() if ctx.eventLoop.inEventLoop { @@ -251,13 +251,13 @@ public final class ServerBootstrap { /// ``` /// public final class ClientBootstrap { - + private let group: EventLoopGroup private var channelInitializer: ((Channel) -> EventLoopFuture<()>)? private var channelOptions = ChannelOptionStorage() private var connectTimeout: TimeAmount = TimeAmount.seconds(10) private var resolver: Resolver? - + /// Create a `ClientBootstrap` on the `EventLoopGroup` `group`. /// /// - parameters: @@ -265,7 +265,7 @@ public final class ClientBootstrap { public init(group: EventLoopGroup) { self.group = group } - + /// Initialize the connected `SocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// @@ -275,7 +275,7 @@ public final class ClientBootstrap { self.channelInitializer = handler return self } - + /// Specifies a `ChannelOption` to be applied to the `SocketChannel`. /// /// - parameters: @@ -294,7 +294,7 @@ public final class ClientBootstrap { self.connectTimeout = timeout return self } - + /// Specifies the `Resolver` to use or `nil` if the default should be used. /// /// - parameters: @@ -321,7 +321,7 @@ public final class ClientBootstrap { } return connector.resolveAndConnect() } - + /// Specify the `address` to connect to for the TCP `Channel` that will be established. /// /// - parameters: @@ -506,7 +506,7 @@ public final class DatagramBootstrap { fileprivate struct ChannelOptionStorage { private var storage: [(Any, (Any, (Channel) -> (Any, Any) -> EventLoopFuture))] = [] - + mutating func put(key: K, value newValue: K.OptionType) { func applier(_ t: Channel) -> (Any, Any) -> EventLoopFuture { @@ -528,7 +528,7 @@ fileprivate struct ChannelOptionStorage { self.storage.append((key, (newValue, applier))) } } - + func applyAll(channel: Channel) -> EventLoopFuture { let applyPromise: EventLoopPromise = channel.eventLoop.newPromise() var it = self.storage.makeIterator() diff --git a/Sources/NIO/ByteBuffer-core.swift b/Sources/NIO/ByteBuffer-core.swift index 1a9d3f2a0..77c195638 100644 --- a/Sources/NIO/ByteBuffer-core.swift +++ b/Sources/NIO/ByteBuffer-core.swift @@ -34,7 +34,7 @@ let sysFree = free /// /// - note: `ByteBufferAllocator` is thread-safe. public struct ByteBufferAllocator { - + /// Create a fresh `ByteBufferAllocator`. In the future the allocator might use for example allocation pools and /// therefore it's recommended to reuse `ByteBufferAllocators` where possible instead of creating fresh ones in /// many places. @@ -217,7 +217,7 @@ public struct ByteBuffer { self.allocator.memcpy(new.bytes, self.bytes.advanced(by: Int(slice.lowerBound)), slice.count) return new } - + public func reallocStorage(capacity: Capacity) { let ptr = self.allocator.realloc(self.bytes, Int(capacity)) /* bind the memory so we can assume it elsewhere to be bound to UInt8 */ @@ -226,7 +226,7 @@ public struct ByteBuffer { self.capacity = capacity self.fullSlice = 0.. self._slice.upperBound { // double the capacity, we may want to use different strategies depending on the actual current capacity later on. var newCapacity = max(1, toCapacity(self.capacity)) - + // double the capacity until the requested capacity can be full-filled repeat { precondition(newCapacity != Capacity.max, "cannot make ByteBuffers larger than \(newCapacity)") @@ -281,7 +281,7 @@ public struct ByteBuffer { newCapacity = Capacity.max } } while newCapacity < index || newCapacity - index < capacity - + self._storage.reallocStorage(capacity: newCapacity) self._slice = _slice.lowerBound..<_slice.lowerBound + newCapacity } @@ -293,7 +293,7 @@ public struct ByteBuffer { assert(newIndex >= 0 && newIndex <= writerIndex) self._readerIndex = newIndex } - + private mutating func moveWriterIndex(to newIndex: Index) { assert(newIndex >= 0 && newIndex <= toCapacity(self._slice.count)) self._writerIndex = newIndex diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index f3dc91201..5cf56e4dd 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -23,7 +23,7 @@ public protocol ChannelCore: class { /// Return the connected `SocketAddress`. func remoteAddress0() throws -> SocketAddress - + /// Register with the `EventLoop` to receive I/O notifications. /// /// - parameters: @@ -36,27 +36,27 @@ public protocol ChannelCore: class { /// - to: The `SocketAddress` to which we should bind the `Channel`. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func bind0(to: SocketAddress, promise: EventLoopPromise?) - + /// Connect to a `SocketAddress`. /// /// - parameters: /// - to: The `SocketAddress` to which we should connect the `Channel`. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func connect0(to: SocketAddress, promise: EventLoopPromise?) - + /// Write the given data to the outbound buffer. /// /// - parameters: /// - data: The data to write, wrapped in a `NIOAny`. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func write0(_ data: NIOAny, promise: EventLoopPromise?) - + /// Try to flush out all previous written messages that are pending. func flush0() - + /// Request that the `Channel` perform a read when data is ready. func read0() - + /// Close the `Channel`. /// /// - parameters: @@ -64,20 +64,20 @@ public protocol ChannelCore: class { /// - mode: The `CloseMode` to apply. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func close0(error: Error, mode: CloseMode, promise: EventLoopPromise?) - + /// Trigger an outbound event. /// /// - parameters: /// - event: The triggered event. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func triggerUserOutboundEvent0(_ event: Any, promise: EventLoopPromise?) - + /// Called when data was read from the `Channel` but it was not consumed by any `ChannelInboundHandler` in the `ChannelPipeline`. /// /// - parameters: /// - data: The data that was read, wrapped in a `NIOAny`. func channelRead0(_ data: NIOAny) - + /// Called when an inbound error was encountered but was not consumed by any `ChannelInboundHandler` in the `ChannelPipeline`. /// /// - parameters: @@ -104,10 +104,10 @@ public protocol Channel: class, ChannelOutboundInvoker { /// The `ChannelPipeline` which handles all I/O events and requests associated with this `Channel`. var pipeline: ChannelPipeline { get } - + /// The local `SocketAddress`. var localAddress: SocketAddress? { get } - + /// The remote peer's `SocketAddress`. var remoteAddress: SocketAddress? { get } @@ -117,13 +117,13 @@ public protocol Channel: class, ChannelOutboundInvoker { /// Set `option` to `value` on this `Channel`. func setOption(option: T, value: T.OptionType) -> EventLoopFuture - + /// Get the value of `option` for this `Channel`. func getOption(option: T) -> EventLoopFuture /// Returns if this `Channel` is currently writable. var isWritable: Bool { get } - + /// Returns if this `Channel` is currently active. Active is defined as the period of time after the /// `channelActive` and before `channelInactive` has fired. The main use for this is to know if `channelActive` /// or `channelInactive` can be expected next when `handlerAdded` was received. @@ -146,13 +146,13 @@ internal protocol SelectableChannel: Channel { /// Returns the `Selectable` which usually contains the file descriptor for the socket. var selectable: SelectableType { get } - + /// The event(s) of interest. var interestedEvent: IOEvent { get } /// Called when the `SelectableChannel` is ready to be written. func writable() - + /// Called when the `SelectableChannel` is ready to be read. func readable() @@ -166,11 +166,11 @@ internal protocol SelectableChannel: Channel { /// Default implementations which will start on the head of the `ChannelPipeline`. extension Channel { - + public func bind(to address: SocketAddress, promise: EventLoopPromise?) { pipeline.bind(to: address, promise: promise) } - + public func connect(to address: SocketAddress, promise: EventLoopPromise?) { pipeline.connect(to: address, promise: promise) } @@ -182,7 +182,7 @@ extension Channel { public func flush() { pipeline.flush() } - + public func writeAndFlush(_ data: NIOAny, promise: EventLoopPromise?) { pipeline.writeAndFlush(data, promise: promise) } @@ -198,7 +198,7 @@ extension Channel { public func register(promise: EventLoopPromise?) { pipeline.register(promise: promise) } - + public func triggerUserOutboundEvent(_ event: Any, promise: EventLoopPromise?) { pipeline.triggerUserOutboundEvent(event, promise: promise) } @@ -207,29 +207,29 @@ extension Channel { /// Provides special extension to make writing data to the `Channel` easier by removing the need to wrap data in `NIOAny` manually. public extension Channel { - + /// Write data into the `Channel`, automatically wrapping with `NIOAny`. /// /// - seealso: `ChannelOutboundInvoker.write`. public func write(_ any: T) -> EventLoopFuture { return self.write(NIOAny(any)) } - + /// Write data into the `Channel`, automatically wrapping with `NIOAny`. /// /// - seealso: `ChannelOutboundInvoker.write`. public func write(_ any: T, promise: EventLoopPromise?) { self.write(NIOAny(any), promise: promise) } - + /// Write and flush data into the `Channel`, automatically wrapping with `NIOAny`. /// /// - seealso: `ChannelOutboundInvoker.writeAndFlush`. public func writeAndFlush(_ any: T) -> EventLoopFuture { return self.writeAndFlush(NIOAny(any)) } - - + + /// Write and flush data into the `Channel`, automatically wrapping with `NIOAny`. /// /// - seealso: `ChannelOutboundInvoker.writeAndFlush`. @@ -251,10 +251,10 @@ public enum ChannelError: Error { /// Unsupported operation triggered on a `Channel`. For example `connect` on a `ServerSocketChannel`. case operationUnsupported - + /// An I/O operation (e.g. read/write/flush) called on a channel that is already closed. case ioOnClosedChannel - + /// Close was called on a channel that is already closed. case alreadyClosed @@ -263,7 +263,7 @@ public enum ChannelError: Error { /// Input-side of the channel is closed. case inputClosed - + /// A read operation reached end-of-file. This usually means the remote peer closed the socket but it's still /// open locally. case eof diff --git a/Sources/NIO/ChannelHandler.swift b/Sources/NIO/ChannelHandler.swift index af908ed2b..2ccf4c88c 100644 --- a/Sources/NIO/ChannelHandler.swift +++ b/Sources/NIO/ChannelHandler.swift @@ -23,7 +23,7 @@ public protocol ChannelHandler: class { /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. func handlerAdded(ctx: ChannelHandlerContext) - + /// Called when this `ChannelHandler` is removed from the `ChannelPipeline`. /// /// - parameters: @@ -35,7 +35,7 @@ public protocol ChannelHandler: class { /// /// We _strongly_ advice against implementing this protocol directly. Please implement `ChannelOutboundHandler`. public protocol _ChannelOutboundHandler: ChannelHandler { - + /// Called to request that the `Channel` register itself for I/O events with its `EventLoop`. /// This should call `ctx.register` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or /// complete the `EventLoopPromise` to let the caller know that the operation completed. @@ -44,7 +44,7 @@ public protocol _ChannelOutboundHandler: ChannelHandler { /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) - + /// Called to request that the `Channel` bind to a specific `SocketAddress`. /// /// This should call `ctx.bind` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or @@ -55,7 +55,7 @@ public protocol _ChannelOutboundHandler: ChannelHandler { /// - to: The `SocketAddress` to which this `Channel` should bind. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func bind(ctx: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) - + /// Called to request that the `Channel` connect to a given `SocketAddress`. /// /// This should call `ctx.connect` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or @@ -66,7 +66,7 @@ public protocol _ChannelOutboundHandler: ChannelHandler { /// - to: The `SocketAddress` to which the the `Channel` should connect. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func connect(ctx: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) - + /// Called to request a write operation. The write operation will write the messages through the /// `ChannelPipeline`. Those are then ready to be flushed to the actual `Channel` when /// `Channel.flush` or `ChannelHandlerContext.flush` is called. @@ -79,7 +79,7 @@ public protocol _ChannelOutboundHandler: ChannelHandler { /// - data: The data to write through the `Channel`, wrapped in a `NIOAny`. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) - + /// Called to request that the `Channel` flush all pending writes. The flush operation will try to flush out all previous written messages /// that are pending. /// @@ -98,7 +98,7 @@ public protocol _ChannelOutboundHandler: ChannelHandler { /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. func read(ctx: ChannelHandlerContext) - + /// Called to request that the `Channel` close itself down`. /// /// This should call `ctx.close` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or @@ -109,7 +109,7 @@ public protocol _ChannelOutboundHandler: ChannelHandler { /// - mode: The `CloseMode` to apply /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) - + /// Called when an user outbound event is triggered. /// /// This should call `ctx.triggerUserOutboundEvent` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or @@ -126,7 +126,7 @@ public protocol _ChannelOutboundHandler: ChannelHandler { /// /// We _strongly_ advice against implementing this protocol directly. Please implement `ChannelInboundHandler`. public protocol _ChannelInboundHandler: ChannelHandler { - + /// Called when the `Channel` has successfully registered with its `EventLoop` to handle I/O. /// /// This should call `ctx.fireChannelRegistered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. @@ -134,7 +134,7 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. func channelRegistered(ctx: ChannelHandlerContext) - + /// Called when the `Channel` has unregistered from its `EventLoop`, and so will no longer be receiving I/O events. /// /// This should call `ctx.fireChannelUnregistered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. @@ -142,7 +142,7 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. func channelUnregistered(ctx: ChannelHandlerContext) - + /// Called when the `Channel` has become active, and is able to send and receive data. /// /// This should call `ctx.fireChannelActive` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. @@ -150,7 +150,7 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. func channelActive(ctx: ChannelHandlerContext) - + /// Called when the `Channel` has become inactive and is no longer able to send and receive data`. /// /// This should call `ctx.fireChannelInactive` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. @@ -158,7 +158,7 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. func channelInactive(ctx: ChannelHandlerContext) - + /// Called when some data has been read from the remote peer. /// /// This should call `ctx.fireChannelRead` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. @@ -167,7 +167,7 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - data: The data read from the remote peer, wrapped in a `NIOAny`. func channelRead(ctx: ChannelHandlerContext, data: NIOAny) - + /// Called when the `Channel` has completed its current read loop, either because no more data is available to read from the transport at this time, or because the `Channel` needs to yield to the event loop to process other I/O events for other `Channel`s. /// If `ChannelOptions.autoRead` is `false` no futher read attempt will be made until `ChannelHandlerContext.read` or `Channel.read` is explicitly called. /// @@ -176,7 +176,7 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. func channelReadComplete(ctx: ChannelHandlerContext) - + /// The writability state of the `Channel` has changed, either because it has buffered more data than the writability high water mark, or because the amount of buffered data has dropped below the writability low water mark. /// You can check the state with `Channel.isWritable`. /// @@ -185,7 +185,7 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. func channelWritabilityChanged(ctx: ChannelHandlerContext) - + /// Called when a user inbound event has been triggered. /// /// This should call `ctx.fireUserInboundEventTriggered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. @@ -194,7 +194,7 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - event: The event. func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) - + /// An error was encountered earlier in the inbound `ChannelPipeline`. /// /// This should call `ctx.fireErrorCaught` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the error. @@ -207,11 +207,11 @@ public protocol _ChannelInboundHandler: ChannelHandler { // Default implementations for the ChannelHandler protocol extension ChannelHandler { - + /// Do nothing by default. public func handlerAdded(ctx: ChannelHandlerContext) { } - + /// Do nothing by default. public func handlerRemoved(ctx: ChannelHandlerContext) { } @@ -222,35 +222,35 @@ extension ChannelHandler { /// These default implementations will just call `ctx.methodName` to forward to the next `_ChannelOutboundHandler` in /// the `ChannelPipeline` until the operation is handled by the `Channel` itself. extension _ChannelOutboundHandler { - + public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { ctx.register(promise: promise) } - + public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { ctx.bind(to: address, promise: promise) } - + public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { ctx.connect(to: address, promise: promise) } - + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { ctx.write(data, promise: promise) } - + public func flush(ctx: ChannelHandlerContext) { ctx.flush() } - + public func read(ctx: ChannelHandlerContext) { ctx.read() } - + public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { ctx.close(mode: mode, promise: promise) } - + public func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { ctx.triggerUserOutboundEvent(event, promise: promise) } @@ -261,39 +261,39 @@ extension _ChannelOutboundHandler { /// These default implementations will just `ctx.fire*` to forward to the next `_ChannelInboundHandler` in /// the `ChannelPipeline` until the operation is handled by the `Channel` itself. extension _ChannelInboundHandler { - + public func channelRegistered(ctx: ChannelHandlerContext) { ctx.fireChannelRegistered() } - + public func channelUnregistered(ctx: ChannelHandlerContext) { ctx.fireChannelUnregistered() } - + public func channelActive(ctx: ChannelHandlerContext) { ctx.fireChannelActive() } - + public func channelInactive(ctx: ChannelHandlerContext) { ctx.fireChannelInactive() } - + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { ctx.fireChannelRead(data) } - + public func channelReadComplete(ctx: ChannelHandlerContext) { ctx.fireChannelReadComplete() } - + public func channelWritabilityChanged(ctx: ChannelHandlerContext) { ctx.fireChannelWritabilityChanged() } - + public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { ctx.fireUserInboundEventTriggered(event) } - + public func errorCaught(ctx: ChannelHandlerContext, error: Error) { ctx.fireErrorCaught(error) } diff --git a/Sources/NIO/ChannelHandlers.swift b/Sources/NIO/ChannelHandlers.swift index 01455fa40..bf7ea2bab 100644 --- a/Sources/NIO/ChannelHandlers.swift +++ b/Sources/NIO/ChannelHandlers.swift @@ -26,10 +26,10 @@ public class BackPressureHandler: ChannnelDuplexHandler { public typealias InboundIn = ByteBuffer public typealias InboundOut = ByteBuffer public typealias OutboundOut = ByteBuffer - + private var pendingRead = false private var writable: Bool = true - + public init() { } public func read(ctx: ChannelHandlerContext) { @@ -39,7 +39,7 @@ public class BackPressureHandler: ChannnelDuplexHandler { pendingRead = true } } - + public func channelWritabilityChanged(ctx: ChannelHandlerContext) { self.writable = ctx.channel.isWritable if writable { @@ -47,15 +47,15 @@ public class BackPressureHandler: ChannnelDuplexHandler { } else { ctx.flush() } - + // Propagate the event as the user may still want to do something based on it. ctx.fireChannelWritabilityChanged() } - + public func handlerRemoved(ctx: ChannelHandlerContext) { mayRead(ctx: ctx) } - + private func mayRead(ctx: ChannelHandlerContext) { if pendingRead { pendingRead = false @@ -70,7 +70,7 @@ public class IdleStateHandler: ChannnelDuplexHandler { public typealias InboundOut = NIOAny public typealias OutboundIn = NIOAny public typealias OutboundOut = NIOAny - + enum IdleStateEvent { /// Will be triggered when no write was performed for the specified amount of time case write @@ -79,7 +79,7 @@ public class IdleStateHandler: ChannnelDuplexHandler { /// Will be triggered when neither read nor write was performed for the specified amount of time case all } - + public let readTimeout: TimeAmount? public let writeTimeout: TimeAmount? public let allTimeout: TimeAmount? @@ -96,7 +96,7 @@ public class IdleStateHandler: ChannnelDuplexHandler { self.writeTimeout = writeTimeout self.allTimeout = allTimeout } - + public func handlerAdded(ctx: ChannelHandlerContext) { if ctx.channel.isActive { initIdleTasks(ctx) @@ -106,7 +106,7 @@ public class IdleStateHandler: ChannnelDuplexHandler { public func handlerRemoved(ctx: ChannelHandlerContext) { cancelIdleTasks(ctx) } - + public func channelActive(ctx: ChannelHandlerContext) { initIdleTasks(ctx) } @@ -117,7 +117,7 @@ public class IdleStateHandler: ChannnelDuplexHandler { } ctx.fireChannelRead(data) } - + public func channelReadComplete(ctx: ChannelHandlerContext) { if (readTimeout != nil || allTimeout != nil) && reading { lastReadTime = DispatchTime.now() @@ -125,33 +125,33 @@ public class IdleStateHandler: ChannnelDuplexHandler { } ctx.fireChannelReadComplete() } - + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { if writeTimeout == nil && allTimeout == nil { ctx.write(data, promise: promise) return } - + let writePromise = promise ?? ctx.eventLoop.newPromise() writePromise.futureResult.whenComplete { self.lastWriteCompleteTime = DispatchTime.now() } ctx.write(data, promise: writePromise) } - + private func shouldReschedule(_ ctx: ChannelHandlerContext) -> Bool { if ctx.channel.isActive { return true } return false } - + private func newReadTimeoutTask(_ ctx: ChannelHandlerContext, _ timeout: TimeAmount) -> (() -> Void) { return { guard self.shouldReschedule(ctx) else { return } - + if self.reading { self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.newReadTimeoutTask(ctx, timeout)) return @@ -161,7 +161,7 @@ public class IdleStateHandler: ChannnelDuplexHandler { if diff >= timeout.nanoseconds { // Reader is idle - set a new timeout and trigger an event through the pipeline self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.newReadTimeoutTask(ctx, timeout)) - + ctx.fireUserInboundEventTriggered(IdleStateEvent.read) } else { // Read occurred before the timeout - set a new timeout with shorter delay. @@ -169,20 +169,20 @@ public class IdleStateHandler: ChannnelDuplexHandler { } } } - + private func newWriteTimeoutTask(_ ctx: ChannelHandlerContext, _ timeout: TimeAmount) -> (() -> Void) { return { guard self.shouldReschedule(ctx) else { return } - + let lastWriteTime = self.lastWriteCompleteTime let diff = DispatchTime.now().uptimeNanoseconds - lastWriteTime.uptimeNanoseconds - + if diff >= timeout.nanoseconds { // Writer is idle - set a new timeout and notify the callback. self.scheduledWriterTask = ctx.eventLoop.scheduleTask(in: timeout, self.newWriteTimeoutTask(ctx, timeout)) - + ctx.fireUserInboundEventTriggered(IdleStateEvent.write) } else { // Write occurred before the timeout - set a new timeout with shorter delay. @@ -196,19 +196,19 @@ public class IdleStateHandler: ChannnelDuplexHandler { guard self.shouldReschedule(ctx) else { return } - + if self.reading { self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.newAllTimeoutTask(ctx, timeout)) return } let lastRead = self.lastReadTime let lastWrite = self.lastWriteCompleteTime - + let diff = Int(DispatchTime.now().uptimeNanoseconds) - Int((lastRead > lastWrite ? lastRead : lastWrite).uptimeNanoseconds) if diff >= timeout.nanoseconds { // Reader is idle - set a new timeout and trigger an event through the pipeline self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.newAllTimeoutTask(ctx, timeout)) - + ctx.fireUserInboundEventTriggered(IdleStateEvent.all) } else { // Read occurred before the timeout - set a new timeout with shorter delay. @@ -216,14 +216,14 @@ public class IdleStateHandler: ChannnelDuplexHandler { } } } - + private func schedule(_ ctx: ChannelHandlerContext, _ amount: TimeAmount?, _ body: @escaping (ChannelHandlerContext, TimeAmount) -> (() -> Void) ) -> Scheduled? { if let timeout = amount { return ctx.eventLoop.scheduleTask(in: timeout, body(ctx, timeout)) } return nil } - + private func initIdleTasks(_ ctx: ChannelHandlerContext) { let now = DispatchTime.now() lastReadTime = now diff --git a/Sources/NIO/ChannelInvoker.swift b/Sources/NIO/ChannelInvoker.swift index e6724b269..3409afdc4 100644 --- a/Sources/NIO/ChannelInvoker.swift +++ b/Sources/NIO/ChannelInvoker.swift @@ -14,25 +14,25 @@ /// Allows users to invoke an "outbound" operation related to a `Channel` that will flow through the `ChannelPipeline` until /// it will finally be executed by the the `ChannelCore` implementation. public protocol ChannelOutboundInvoker { - + /// Register on an `EventLoop` and so have all its IO handled. /// /// - returns: the future which will be notified once the operation completes. func register() -> EventLoopFuture - + /// Register on an `EventLoop` and so have all its IO handled. /// /// - parameters: /// - promise: the `EventLoopPromise` that will be notified once the operation completes, /// or `nil` if not interested in the outcome of the operation. func register(promise: EventLoopPromise?) - + /// Bind to a `SocketAddress`. /// - parameters: /// - to: the `SocketAddress` to which we should bind the `Channel`. /// - returns: the future which will be notified once the operation completes. func bind(to: SocketAddress) -> EventLoopFuture - + /// Bind to a `SocketAddress`. /// - parameters: /// - to: the `SocketAddress` to which we should bind the `Channel`. @@ -45,14 +45,14 @@ public protocol ChannelOutboundInvoker { /// - to: the `SocketAddress` to which we should connect the `Channel`. /// - returns: the future which will be notified once the operation completes. func connect(to: SocketAddress) -> EventLoopFuture - + /// Connect to a `SocketAddress`. /// - parameters: /// - to: the `SocketAddress` to which we should connect the `Channel`. /// - promise: the `EventLoopPromise` that will be notified once the operation completes, /// or `nil` if not interested in the outcome of the operation. func connect(to: SocketAddress, promise: EventLoopPromise?) - + /// Write data to the remote peer. /// /// Be aware that to be sure that data is really written to the remote peer you need to call `flush` or use `writeAndFlush`. @@ -62,7 +62,7 @@ public protocol ChannelOutboundInvoker { /// - data: the data to write /// - returns: the future which will be notified once the operation completes. func write(_ data: NIOAny) -> EventLoopFuture - + /// Write data to the remote peer. /// /// Be aware that to be sure that data is really written to the remote peer you need to call `flush` or use `writeAndFlush`. @@ -76,14 +76,14 @@ public protocol ChannelOutboundInvoker { /// Flush data that was previously written via `write` to the remote peer. func flush() - + /// Shortcut for calling `write` and `flush`. /// /// - parameters: /// - data: the data to write /// - returns: the future which will be notified once the `write` operation completes. func writeAndFlush(_ data: NIOAny) -> EventLoopFuture - + /// Shortcut for calling `write` and `flush`. /// /// - parameters: @@ -91,7 +91,7 @@ public protocol ChannelOutboundInvoker { /// - promise: the `EventLoopPromise` that will be notified once the `write` operation completes, /// or `nil` if not interested in the outcome of the operation. func writeAndFlush(_ data: NIOAny, promise: EventLoopPromise?) - + /// Signal that we want to read from the `Channel` once there is data ready. /// /// If `ChannelOptions.autoRead` is set for a `Channel` (which is the default) this method is automatically invoked by the transport implementation, @@ -105,7 +105,7 @@ public protocol ChannelOutboundInvoker { /// - mode: the `CloseMode` that is used /// - returns: the future which will be notified once the operation completes. func close(mode: CloseMode) -> EventLoopFuture - + /// Close the `Channel` and so the connection if one exists. /// /// - parameters: @@ -113,21 +113,21 @@ public protocol ChannelOutboundInvoker { /// - promise: the `EventLoopPromise` that will be notified once the operation completes, /// or `nil` if not interested in the outcome of the operation. func close(mode: CloseMode, promise: EventLoopPromise?) - + /// Trigger a custom user outbound event which will flow through the `ChannelPipeline`. /// /// - parameters: /// - event: the event itself. /// - returns: the future which will be notified once the operation completes. func triggerUserOutboundEvent(_ event: Any) -> EventLoopFuture - + /// Trigger a custom user outbound event which will flow through the `ChannelPipeline`. /// /// - parameters: /// - promise: the `EventLoopPromise` that will be notified once the operation completes, /// or `nil` if not interested in the outcome of the operation. func triggerUserOutboundEvent(_ event: Any, promise: EventLoopPromise?) - + /// The `EventLoop` which is used by this `ChannelOutboundInvoker` for execution. var eventLoop: EventLoop { get } } @@ -142,43 +142,43 @@ extension ChannelOutboundInvoker { register(promise: promise) return promise.futureResult } - + public func bind(to address: SocketAddress) -> EventLoopFuture { let promise = newPromise() bind(to: address, promise: promise) return promise.futureResult } - + public func connect(to address: SocketAddress) -> EventLoopFuture { let promise = newPromise() connect(to: address, promise: promise) return promise.futureResult } - + public func write(_ data: NIOAny) -> EventLoopFuture { let promise = newPromise() write(data, promise: promise) return promise.futureResult } - + public func writeAndFlush(_ data: NIOAny) -> EventLoopFuture { let promise = newPromise() writeAndFlush(data, promise: promise) return promise.futureResult } - + public func close(mode: CloseMode = .all) -> EventLoopFuture { let promise = newPromise() close(mode: mode, promise: promise) return promise.futureResult } - + public func triggerUserOutboundEvent(_ event: Any) -> EventLoopFuture { let promise = newPromise() triggerUserOutboundEvent(event, promise: promise) return promise.futureResult } - + private func newPromise() -> EventLoopPromise { return eventLoop.newPromise() } @@ -186,34 +186,34 @@ extension ChannelOutboundInvoker { /// Fire inbound events related to a `Channel` through the `ChannelPipeline` until its end is reached or it's consumed by a `ChannelHandler`. public protocol ChannelInboundInvoker { - + /// Called once a `Channel` was registered to its `EventLoop` and so IO will be processed. func fireChannelRegistered() - + /// Called once a `Channel` was unregistered from its `EventLoop` which means no IO will be handled for a `Channel` anymore. func fireChannelUnregistered() - + /// Called once a `Channel` becomes active. /// /// What active means depends on the `Channel` implementation and semantics. /// For example for TCP it means the `Channel` is connected to the remote peer. func fireChannelActive() - + /// Called once a `Channel` becomes inactive. /// /// What inactive means depends on the `Channel` implementation and semantics. /// For example for TCP it means the `Channel` was disconnected from the remote peer and closed. func fireChannelInactive() - + /// Called once there is some data read for a `Channel` that needs processing. /// /// - parameters: /// - data: the data that was read and is ready to be processed. func fireChannelRead(_ data: NIOAny) - + /// Called once there is no more data to read immediately on a `Channel`. Any new data received will be handled later. func fireChannelReadComplete() - + /// Called when a `Channel`'s writable state changes. /// /// The writability state of a Channel depends on watermarks that can be set via `Channel.setOption` and how much data @@ -223,7 +223,7 @@ public protocol ChannelInboundInvoker { /// protocol and other semantics. But for example you may want to stop writing to the `Channel` until `Channel.writable` becomes /// `true` again or stop reading at all. func fireChannelWritabilityChanged() - + /// Called when an inbound operation `Error` was caught. /// /// Be aware that for inbound operations this method is called while for outbound operations defined in `ChannelOutboundInvoker` @@ -232,7 +232,7 @@ public protocol ChannelInboundInvoker { /// - parameters: /// - error: the error we encountered. func fireErrorCaught(_ error: Error) - + /// Trigger a custom user inbound event which will flow through the `ChannelPipeline`. /// /// - parameters: @@ -248,11 +248,11 @@ public enum CloseMode { /// Close the output (writing) side of the `Channel` without closing the actual file descriptor. /// This is an optional mode which means it may not be supported by all `Channel` implementations. case output - + /// Close the input (reading) side of the `Channel` without closing the actual file descriptor. /// This is an optional mode which means it may not be supported by all `Channel` implementations. case input - + /// Close the whole `Channel (file descriptor). case all } diff --git a/Sources/NIO/ChannelOption.swift b/Sources/NIO/ChannelOption.swift index 6ef19d3c3..1b6bdc500 100644 --- a/Sources/NIO/ChannelOption.swift +++ b/Sources/NIO/ChannelOption.swift @@ -16,10 +16,10 @@ public protocol ChannelOption { associatedtype AssociatedValueType associatedtype OptionType - + /// The value of the `ChannelOption`. var value: AssociatedValueType { get } - + /// The type of the `ChannelOption` var type: OptionType.Type { get } } @@ -52,9 +52,9 @@ public enum SocketOption: ChannelOption { public typealias AssociatedValueType = (SocketOptionLevel, SocketOptionName) public typealias OptionType = (SocketOptionValue) - + case const(AssociatedValueType) - + /// Create a new `SocketOption`. /// /// - parameters: @@ -76,7 +76,7 @@ public enum SocketOption: ChannelOption { public enum AllocatorOption: ChannelOption { public typealias AssociatedValueType = () public typealias OptionType = ByteBufferAllocator - + case const(()) } @@ -84,7 +84,7 @@ public enum AllocatorOption: ChannelOption { public enum RecvAllocatorOption: ChannelOption { public typealias AssociatedValueType = () public typealias OptionType = RecvByteBufferAllocator - + case const(()) } @@ -93,7 +93,7 @@ public enum RecvAllocatorOption: ChannelOption { public enum AutoReadOption: ChannelOption { public typealias AssociatedValueType = () public typealias OptionType = Bool - + case const(()) } @@ -103,7 +103,7 @@ public enum AutoReadOption: ChannelOption { public enum WriteSpinOption: ChannelOption { public typealias AssociatedValueType = () public typealias OptionType = UInt - + case const(()) } @@ -112,7 +112,7 @@ public enum WriteSpinOption: ChannelOption { public enum MaxMessagesPerReadOption: ChannelOption { public typealias AssociatedValueType = () public typealias OptionType = UInt - + case const(()) } @@ -120,7 +120,7 @@ public enum MaxMessagesPerReadOption: ChannelOption { public enum BacklogOption: ChannelOption { public typealias AssociatedValueType = () public typealias OptionType = Int32 - + case const(()) } @@ -131,13 +131,13 @@ public struct WriteBufferWaterMark { /// When the amount of buffered bytes in the `Channel`s outbound buffer drops below this value the `Channel` will be /// marked as writable again (after it was non-writable). public let low: Int - + /// The high mark setting for a `Channel`. /// /// When the amount of buffered bytes in the `Channel`s outbound exceeds this value the `Channel` will be /// marked as non-writable. It will be marked as writable again once the amount of buffered bytes drops below `low`. public let high: Int - + /// Create a new instance. /// /// Valid initialization is restricted to `1 <= low <= high`. @@ -161,7 +161,7 @@ public struct WriteBufferWaterMark { public enum WriteBufferWaterMarkOption: ChannelOption { public typealias AssociatedValueType = () public typealias OptionType = WriteBufferWaterMark - + case const(()) } @@ -182,7 +182,7 @@ public enum ConnectTimeoutOption: ChannelOption { public enum AllowRemoteHalfClosureOption: ChannelOption { public typealias AssociatedValueType = () public typealias OptionType = Bool - + case const(()) } @@ -199,22 +199,22 @@ public struct ChannelOptions { /// - seealso: `AutoReadOption`. public static let autoRead = AutoReadOption.const(()) - + /// - seealso: `MaxMessagesPerReadOption`. public static let maxMessagesPerRead = MaxMessagesPerReadOption.const(()) - + /// - seealso: `BacklogOption`. public static let backlog = BacklogOption.const(()) - + /// - seealso: `WriteSpinOption`. public static let writeSpin = WriteSpinOption.const(()) - + /// - seealso: `WriteBufferWaterMarkOption`. public static let writeBufferWaterMark = WriteBufferWaterMarkOption.const(()) /// - seealso: `ConnectTimeoutOption`. public static let connectTimeout = ConnectTimeoutOption.const(()) - + /// - seealso: `AllowRemoteHalfClosureOption`. public static let allowRemoteHalfClosure = AllowRemoteHalfClosureOption.const(()) } diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index 7593643c1..1e2eab6d2 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -714,7 +714,7 @@ private final class HeadChannelHandler: _ChannelOutboundHandler { func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { ctx.channel._unsafe.triggerUserOutboundEvent0(event, promise: promise) } - + } private extension CloseMode { @@ -802,7 +802,7 @@ public final class ChannelHandlerContext: ChannelInvoker { public var channel: Channel { return self.pipeline.channel } - + public var handler: ChannelHandler { return self.inboundHandler ?? self.outboundHandler! } diff --git a/Sources/NIO/CircularBuffer.swift b/Sources/NIO/CircularBuffer.swift index 11fd77d2e..fe4334144 100644 --- a/Sources/NIO/CircularBuffer.swift +++ b/Sources/NIO/CircularBuffer.swift @@ -25,32 +25,32 @@ public protocol AppendableCollection: Collection { /// expansions from happening frequently. Expansions will always force an allocation and a copy to happen. public struct CircularBuffer: CustomStringConvertible, AppendableCollection { private var buffer: ContiguousArray - + /// The capacity of the underlying buffer private var bufferCapacity: Int - + /// The index into the buffer of the first item private var startIdx = 0 - + /// The index into the buffer of the next free slot private var endIdx = 0 - + /// The number of items in the ring part of this buffer private var ringLength = 0 - + /// Allocates a buffer that can hold up to `initialRingCapacity` elements and initialise an empty ring backed by /// the buffer. When the ring grows to more than `initialRingCapacity` elements the buffer will be expanded. public init(initialRingCapacity: Int) { self.bufferCapacity = initialRingCapacity self.buffer = ContiguousArray(repeating: nil, count: Int(initialRingCapacity)) } - + /// Append an element to the end of the ring buffer. /// /// Amortized *O(1)* public mutating func append(_ value: E) { let expandBuf: Bool = self.bufferCapacity == self.ringLength - + if expandBuf { var newBacking: ContiguousArray = [] let newCapacity = Swift.max(1, 2 * self.bufferCapacity) @@ -66,26 +66,26 @@ public struct CircularBuffer: CustomStringConvertible, AppendableCollection { self.bufferCapacity = newCapacity precondition(self.bufferCapacity == self.buffer.count) } - + self.buffer[self.endIdx] = value self.ringLength += 1 self.endIdx = (self.endIdx + 1) % self.bufferCapacity } - + /// Remove the front element of the ring buffer. /// /// *O(1)* public mutating func removeFirst() -> E { precondition(self.ringLength != 0) - + let value = self.buffer[self.startIdx] self.buffer[startIdx] = nil self.ringLength -= 1 self.startIdx = (self.startIdx + 1) % self.bufferCapacity - + return value! } - + /// Return the first element of the ring. /// /// *O(1)* @@ -126,7 +126,7 @@ public struct CircularBuffer: CustomStringConvertible, AppendableCollection { return Slice(base: self, bounds: bounds) } } - + /// Return all valid indices of the ring. public var indices: CountableRange { return 0.. DecodingState - + /// This method is called once, when the `ChannelHandlerContext` goes inactive (i.e. when `channelInactive` is fired) /// /// - parameters: @@ -60,19 +60,19 @@ public protocol ByteToMessageDecoder: ChannelInboundHandler where InboundIn == B /// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called // again when more data is present in the `ByteBuffer`. func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState - + /// Called once this `ByteToMessageDecoder` is removed from the `ChannelPipeline`. /// /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. func decoderRemoved(ctx: ChannelHandlerContext) - + /// Called when this `ByteToMessageDecoder` is added to the `ChannelPipeline`. /// /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. func decoderAdded(ctx: ChannelHandlerContext) - + /// Determine if the read bytes in the given `ByteBuffer` should be reclaimed and their associated memory freed. /// Be aware that reclaiming memory may involve memory copies and so is not free. /// @@ -106,12 +106,12 @@ extension ByteToMessageDecoder { } else { self.cumulationBuffer = buffer } - + ctx.withThrowingToFireErrorAndClose { // Running decode method until either the user returned `.needMoreData` or an error occured. while try decode(ctx: ctx, buffer: &buffer) == .`continue` && buffer.readableBytes > 0 { } } - + if buffer.readableBytes > 0 { if self.shouldReclaimBytes(buffer: buffer) { buffer.discardReadBytes() @@ -121,7 +121,7 @@ extension ByteToMessageDecoder { cumulationBuffer = nil } } - + /// Call `decodeLast` before forward the event throught the pipeline. public func channelInactive(ctx: ChannelHandlerContext) { if var buffer = cumulationBuffer { @@ -129,18 +129,18 @@ extension ByteToMessageDecoder { // Running decodeLast method until either the user returned `.needMoreData` or an error occured. while try decodeLast(ctx: ctx, buffer: &buffer) == .`continue` && buffer.readableBytes > 0 { } } - + // Once the Channel goes inactive we can just drop all previous buffered data. cumulationBuffer = nil } - + ctx.fireChannelInactive() } - + public func handlerAdded(ctx: ChannelHandlerContext) { decoderAdded(ctx: ctx) } - + public func handlerRemoved(ctx: ChannelHandlerContext) { if let buffer = cumulationBuffer as? InboundOut { ctx.fireChannelRead(self.wrapInboundOut(buffer)) @@ -156,7 +156,7 @@ extension ByteToMessageDecoder { public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { return try decode(ctx: ctx, buffer: &buffer) } - + /// Do nothing by default. public func decoderRemoved(ctx: ChannelHandlerContext) { } @@ -181,7 +181,7 @@ extension ByteToMessageDecoder { /// `ChannelOutboundHandler` which allows users to encode custom messages to a `ByteBuffer` easily. public protocol MessageToByteEncoder: ChannelOutboundHandler where OutboundOut == ByteBuffer { - + /// Called once there is data to encode. The used `ByteBuffer` is allocated by `allocateOutBuffer`. /// /// - parameters: @@ -189,7 +189,7 @@ public protocol MessageToByteEncoder: ChannelOutboundHandler where OutboundOut = /// - data: The data to encode into a `ByteBuffer`. /// - out: The `ByteBuffer` into which we want to encode. func encode(ctx: ChannelHandlerContext, data: OutboundIn, out: inout ByteBuffer) throws - + /// Returns a `ByteBuffer` to be used by `encode`. /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. @@ -199,7 +199,7 @@ public protocol MessageToByteEncoder: ChannelOutboundHandler where OutboundOut = } extension MessageToByteEncoder { - + /// Encodes the data into a `ByteBuffer` and writes it. public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { do { @@ -211,7 +211,7 @@ extension MessageToByteEncoder { promise?.fail(error: err) } } - + /// Default implementation which just allocates a `ByteBuffer` with capacity of `256`. public func allocateOutBuffer(ctx: ChannelHandlerContext, data: OutboundIn) throws -> ByteBuffer { return ctx.channel.allocator.buffer(capacity: 256) diff --git a/Sources/NIO/Embedded.swift b/Sources/NIO/Embedded.swift index 8a9a43898..2c0d9cec1 100644 --- a/Sources/NIO/Embedded.swift +++ b/Sources/NIO/Embedded.swift @@ -60,7 +60,7 @@ public class EmbeddedEventLoop: EventLoop { var tasks = CircularBuffer<() -> Void>(initialRingCapacity: 2) public init() { } - + public func scheduleTask(in: TimeAmount, _ task: @escaping () throws-> (T)) -> Scheduled { let promise: EventLoopPromise = newPromise() let readyTime = now + UInt64(`in`.nanoseconds) @@ -78,7 +78,7 @@ public class EmbeddedEventLoop: EventLoop { scheduledTasks.push(task) return scheduled } - + // We're not really running a loop here. Tasks aren't run until run() is called, // at which point we run everything that's been submitted. Anything newly submitted // either gets on that train if it's still moving or waits until the next call to run(). @@ -140,11 +140,11 @@ public class EmbeddedEventLoop: EventLoop { class EmbeddedChannelCore: ChannelCore { var isOpen: Bool = true var isActive: Bool = false - + var eventLoop: EventLoop var closePromise: EventLoopPromise var error: Error? - + private let pipeline: ChannelPipeline init(pipeline: ChannelPipeline, eventLoop: EventLoop) { @@ -152,7 +152,7 @@ class EmbeddedChannelCore: ChannelCore { self.pipeline = pipeline self.eventLoop = eventLoop } - + deinit { assert(self.pipeline.destroyed, "leaked an open EmbeddedChannel, maybe forgot to call channel.finish()?") isOpen = false @@ -161,7 +161,7 @@ class EmbeddedChannelCore: ChannelCore { var outboundBuffer: [IOData] = [] var inboundBuffer: [NIOAny] = [] - + func localAddress0() throws -> SocketAddress { throw ChannelError.operationUnsupported } @@ -182,7 +182,7 @@ class EmbeddedChannelCore: ChannelCore { isActive = false pipeline.fireChannelInactive0() pipeline.fireChannelUnregistered0() - + eventLoop.execute { // ensure this is executed in a delayed fashion as the users code may still traverse the pipeline self.pipeline.removeHandlers() @@ -221,21 +221,21 @@ class EmbeddedChannelCore: ChannelCore { func read0() { // NOOP } - + public final func triggerUserOutboundEvent0(_ event: Any, promise: EventLoopPromise?) { promise?.succeed(result: ()) } - + func channelRead0(_ data: NIOAny) { addToBuffer(buffer: &inboundBuffer, data: data) } - + public func errorCaught0(error: Error) { if self.error == nil { self.error = error } } - + private func addToBuffer(buffer: inout [T], data: T) { buffer.append(data) } @@ -251,7 +251,7 @@ public class EmbeddedChannel: Channel { public var _unsafe: ChannelCore { return channelcore } - + public var pipeline: ChannelPipeline { return _pipeline } @@ -259,14 +259,14 @@ public class EmbeddedChannel: Channel { public var isWritable: Bool { return true } - + public func finish() throws -> Bool { try close().wait() (self.eventLoop as! EmbeddedEventLoop).run() try throwIfErrorCaught() return !channelcore.outboundBuffer.isEmpty || !channelcore.inboundBuffer.isEmpty } - + private var _pipeline: ChannelPipeline! public var allocator: ByteBufferAllocator = ByteBufferAllocator() public var eventLoop: EventLoop = EmbeddedEventLoop() @@ -276,27 +276,27 @@ public class EmbeddedChannel: Channel { // Embedded channels never have parents. public let parent: Channel? = nil - + public func readOutbound() -> IOData? { return readFromBuffer(buffer: &channelcore.outboundBuffer) } - + public func readInbound() -> T? { return readFromBuffer(buffer: &channelcore.inboundBuffer) } - + @discardableResult public func writeInbound(_ data: T) throws -> Bool { pipeline.fireChannelRead(NIOAny(data)) pipeline.fireChannelReadComplete() try throwIfErrorCaught() return !channelcore.inboundBuffer.isEmpty } - + @discardableResult public func writeOutbound(_ data: T) throws -> Bool { try writeAndFlush(NIOAny(data)).wait() return !channelcore.outboundBuffer.isEmpty } - + public func throwIfErrorCaught() throws { if let error = channelcore.error { channelcore.error = nil @@ -317,7 +317,7 @@ public class EmbeddedChannel: Channel { } return (buffer.removeFirst().forceAs(type: T.self)) } - + /// Create a new instance. /// /// During creation it will automatically also register itself on the `EmbeddedEventLoop`. @@ -328,12 +328,12 @@ public class EmbeddedChannel: Channel { public init(handler: ChannelHandler? = nil, loop: EmbeddedEventLoop = EmbeddedEventLoop()) { self.eventLoop = loop self._pipeline = ChannelPipeline(channel: self) - + if let handler = handler { // This will be propagated via fireErrorCaught _ = try? _pipeline.add(handler: handler).wait() } - + // This will never throw... _ = try? register().wait() } diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index 1ce12e3f1..c5bfff6ba 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -23,7 +23,7 @@ import NIOPriorityQueue public struct Scheduled { private let promise: EventLoopPromise private let cancellationTask: () -> Void - + init(promise: EventLoopPromise, cancellationTask: @escaping () -> Void) { self.promise = promise promise.futureResult.whenFailure { error in @@ -36,7 +36,7 @@ public struct Scheduled { } self.cancellationTask = cancellationTask } - + /// Try to cancel the execution of the scheduled task. /// /// Whether this is successful depends on whether the execution of the task already begun. @@ -44,7 +44,7 @@ public struct Scheduled { public func cancel() { promise.fail(error: EventLoopError.cancelled) } - + /// Returns the `EventLoopFuture` which will be notified once the execution of the scheduled task completes. public var futureResult: EventLoopFuture { return promise.futureResult @@ -80,7 +80,7 @@ public struct Scheduled { public protocol EventLoop: EventLoopGroup { /// Returns `true` if the current `Thread` is the same as the `Thread` that is tied to this `EventLoop`. `false` otherwise. var inEventLoop: Bool { get } - + /// Submit a given task to be executed by the `EventLoop` func execute(_ task: @escaping () -> Void) @@ -90,7 +90,7 @@ public protocol EventLoop: EventLoopGroup { /// - task: The closure that will be submited to the `EventLoop` for execution. /// - returns: `EventLoopFuture` that is notified once the task was executed. func submit(_ task: @escaping () throws-> (T)) -> EventLoopFuture - + /// Schedule a `task` that is executed by this `SelectableEventLoop` after the given amount of time. func scheduleTask(in: TimeAmount, _ task: @escaping () throws-> (T)) -> Scheduled } @@ -105,7 +105,7 @@ public struct TimeAmount { private init(_ nanoseconds: Int) { self.nanoseconds = nanoseconds } - + /// Creates a new `TimeAmount` for the given amount of nanoseconds. /// /// - parameters: @@ -114,7 +114,7 @@ public struct TimeAmount { public static func nanoseconds(_ amount: Int) -> TimeAmount { return TimeAmount(amount) } - + /// Creates a new `TimeAmount` for the given amount of microseconds. /// /// - parameters: @@ -132,7 +132,7 @@ public struct TimeAmount { public static func milliseconds(_ amount: Int) -> TimeAmount { return TimeAmount(amount * 1000 * 1000) } - + /// Creates a new `TimeAmount` for the given amount of seconds. /// /// - parameters: @@ -141,7 +141,7 @@ public struct TimeAmount { public static func seconds(_ amount: Int) -> TimeAmount { return TimeAmount(amount * 1000 * 1000 * 1000) } - + /// Creates a new `TimeAmount` for the given amount of minutes. /// /// - parameters: @@ -207,11 +207,11 @@ extension EventLoop { public func newSucceededFuture(result: T) -> EventLoopFuture { return EventLoopFuture(eventLoop: self, result: result, file: "n/a", line: 0) } - + public func next() -> EventLoop { return self } - + public func close() throws { // Do nothing } @@ -282,10 +282,10 @@ internal final class SelectableEventLoop: EventLoop { private var scheduledTasks = PriorityQueue(ascending: true) private let tasksLock = Lock() private var lifecycleState: EventLoopLifecycleState = .open - + private let _iovecs: UnsafeMutablePointer private let _storageRefs: UnsafeMutablePointer> - + let iovecs: UnsafeMutableBufferPointer let storageRefs: UnsafeMutableBufferPointer> @@ -294,7 +294,7 @@ internal final class SelectableEventLoop: EventLoop { private let _addresses: UnsafeMutablePointer let msgs: UnsafeMutableBufferPointer let addresses: UnsafeMutableBufferPointer - + /// Creates a new `SelectableEventLoop` instance that is tied to the given `pthread_t`. private let promiseCreationStoreLock = Lock() @@ -325,14 +325,14 @@ internal final class SelectableEventLoop: EventLoop { self.msgs = UnsafeMutableBufferPointer(start: _msgs, count: Socket.writevLimitIOVectors) self.addresses = UnsafeMutableBufferPointer(start: _addresses, count: Socket.writevLimitIOVectors) } - + deinit { _iovecs.deallocate() _storageRefs.deallocate() _msgs.deallocate() _addresses.deallocate() } - + /// Register the given `SelectableChannel` with this `SelectableEventLoop`. After this point all I/O for the `SelectableChannel` will be processed by this `SelectableEventLoop` until it /// is deregistered by calling `deregister`. public func register(channel: C) throws { @@ -355,14 +355,14 @@ internal final class SelectableEventLoop: EventLoop { } try selector.deregister(selectable: channel.selectable) } - + /// Register the given `SelectableChannel` with this `SelectableEventLoop`. This should be done whenever `channel.interestedEvents` has changed and it should be taken into account when /// waiting for new I/O for the given `SelectableChannel`. public func reregister(channel: C) throws { assert(inEventLoop) try selector.reregister(selectable: channel.selectable, interested: channel.interestedEvent) } - + public var inEventLoop: Bool { return thread.isCurrent } @@ -378,33 +378,33 @@ internal final class SelectableEventLoop: EventLoop { }, { error in promise.fail(error: error) },`in`) - + let scheduled = Scheduled(promise: promise, cancellationTask: { self.tasksLock.lock() self.scheduledTasks.remove(task) self.tasksLock.unlock() self.wakeupSelector() }) - + schedule0(task) return scheduled } - + public func execute(_ task: @escaping () -> Void) { schedule0(ScheduledTask(task, { error in // do nothing }, .nanoseconds(0))) } - + /// Add the `ScheduledTask` to be executed. private func schedule0(_ task: ScheduledTask) { tasksLock.lock() scheduledTasks.push(task) tasksLock.unlock() - + wakeupSelector() } - + /// Wake the `Selector` which means `Selector.whenReady(...)` will unblock. private func wakeupSelector() { do { @@ -419,7 +419,7 @@ internal final class SelectableEventLoop: EventLoop { guard channel.selectable.isOpen else { return } - + switch ev { case .write: channel.writable() @@ -427,7 +427,7 @@ internal final class SelectableEventLoop: EventLoop { channel.readable() case .all: channel.writable() - + guard channel.selectable.isOpen else { return } @@ -448,7 +448,7 @@ internal final class SelectableEventLoop: EventLoop { // No tasks to handle so just block return .block } - + let nextReady = sched.readyIn(DispatchTime.now()) if nextReady <= .nanoseconds(0) { @@ -458,19 +458,19 @@ internal final class SelectableEventLoop: EventLoop { return .blockUntilTimeout(nextReady) } } - + /// Start processing I/O and tasks for this `SelectableEventLoop`. This method will continue running (and so block) until the `SelectableEventLoop` is closed. public func run() throws { precondition(self.inEventLoop, "tried to run the EventLoop on the wrong thread.") defer { var tasksCopy = ContiguousArray() - + tasksLock.lock() while let sched = scheduledTasks.pop() { tasksCopy.append(sched) } tasksLock.unlock() - + // Fail all the scheduled tasks. while let task = tasksCopy.first { task.fail(error: EventLoopError.shutdown) @@ -480,7 +480,7 @@ internal final class SelectableEventLoop: EventLoop { // Block until there are events to handle or the selector was woken up /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ try withAutoReleasePool { - + try selector.whenReady(strategy: currentSelectorStrategy()) { ev in switch ev.registration { case .serverSocketChannel(let chan, _): @@ -492,7 +492,7 @@ internal final class SelectableEventLoop: EventLoop { } } } - + // We need to ensure we process all tasks, even if a task added another task again while true { // TODO: Better locking @@ -505,7 +505,7 @@ internal final class SelectableEventLoop: EventLoop { // We only fetch the time one time as this may be expensive and is generally good enough as if we miss anything we will just do a non-blocking select again anyway. let now = DispatchTime.now() - + // Make a copy of the tasks so we can execute these while not holding the lock anymore while let task = scheduledTasks.peek(), task.readyIn(now) <= .nanoseconds(0) { tasksCopy.append(task.task) @@ -514,24 +514,24 @@ internal final class SelectableEventLoop: EventLoop { } tasksLock.unlock() - + // all pending tasks are set to occur in the future, so we can stop looping. if tasksCopy.count == 0 { break } - + // Execute all the tasks that were summited while let task = tasksCopy.first { /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ withAutoReleasePool { task() } - + _ = tasksCopy.removeFirst() } } } - + // This EventLoop was closed so also close the underlying selector. try self.selector.close() } @@ -639,7 +639,7 @@ typealias ThreadInitializer = (Thread) -> Void /// An `EventLoopGroup` which will create multiple `EventLoop`s, each tied to its own `Thread`. final public class MultiThreadedEventLoopGroup: EventLoopGroup { - + private let index = Atomic(value: 0) private let eventLoops: [SelectableEventLoop] @@ -655,7 +655,7 @@ final public class MultiThreadedEventLoopGroup: EventLoopGroup { loopUpAndRunningGroup.enter() Thread.spawnAndRun(name: name) { t in initializer(t) - + do { /* we try! this as this must work (just setting up kqueue/epoll) or else there's not much we can do here */ let l = try! SelectableEventLoop(thread: t) @@ -683,7 +683,7 @@ final public class MultiThreadedEventLoopGroup: EventLoopGroup { let initializers: [ThreadInitializer] = Array(repeating: { _ in }, count: numThreads) self.init(threadInitializers: initializers) } - + /// Creates a `MultiThreadedEventLoopGroup` instance which uses the given `ThreadInitializer`s. One `Thread` per `ThreadInitializer` is created and used. /// /// - arguments: @@ -697,11 +697,11 @@ final public class MultiThreadedEventLoopGroup: EventLoopGroup { return ev } } - + public func next() -> EventLoop { return eventLoops[abs(index.add(1) % eventLoops.count)] } - + internal func unsafeClose() throws { for loop in eventLoops { // TODO: Should we log this somehow or just rethrow the first error ? @@ -741,20 +741,20 @@ private final class ScheduledTask { let task: () -> Void private let failFn: (Error) ->() private let readyTime: Int - + init(_ task: @escaping () -> Void, _ failFn: @escaping (Error) -> Void, _ time: TimeAmount) { self.task = task self.failFn = failFn self.readyTime = time.nanoseconds + Int(DispatchTime.now().uptimeNanoseconds) } - + func readyIn(_ t: DispatchTime) -> TimeAmount { if readyTime < t.uptimeNanoseconds { return .nanoseconds(0) } return .nanoseconds(readyTime - Int(t.uptimeNanoseconds)) } - + func fail(error: Error) { failFn(error) } @@ -779,13 +779,13 @@ extension ScheduledTask: Comparable { public enum EventLoopError: Error { /// An operation was executed that is not supported by the `EventLoop` case unsupportedOperation - + /// An scheduled task was cancelled. case cancelled - + /// The `EventLoop` was shutdown already. case shutdown - + /// Shutting down the `EventLoop` failed. case shutdownFailed } diff --git a/Sources/NIO/EventLoopFuture.swift b/Sources/NIO/EventLoopFuture.swift index c9075addf..0a91a1556 100644 --- a/Sources/NIO/EventLoopFuture.swift +++ b/Sources/NIO/EventLoopFuture.swift @@ -33,7 +33,7 @@ private struct CallbackList: ExpressibleByArrayLiteral { typealias Element = () -> CallbackList var firstCallback: Element? var furtherCallbacks: [Element]? - + init() { firstCallback = nil furtherCallbacks = nil @@ -60,7 +60,7 @@ private struct CallbackList: ExpressibleByArrayLiteral { } } } - + private func allCallbacks() -> [Element] { switch (self.firstCallback, self.furtherCallbacks) { case (.none, _): @@ -71,7 +71,7 @@ private struct CallbackList: ExpressibleByArrayLiteral { return [first]+others } } - + func _run() { switch (self.firstCallback, self.furtherCallbacks) { case (.none, _): @@ -111,7 +111,7 @@ private struct CallbackList: ExpressibleByArrayLiteral { } } } - + } /// A promise to provide a result later. @@ -319,17 +319,17 @@ public final class EventLoopFuture { fileprivate convenience init(eventLoop: EventLoop, file: StaticString, line: UInt) { self.init(eventLoop: eventLoop, value: nil, file: file, line: line) } - + /// A EventLoopFuture that has already succeeded convenience init(eventLoop: EventLoop, result: T, file: StaticString, line: UInt) { self.init(eventLoop: eventLoop, value: .success(result), file: file, line: line) } - + /// A EventLoopFuture that has already failed convenience init(eventLoop: EventLoop, error: Error, file: StaticString, line: UInt) { self.init(eventLoop: eventLoop, value: .failure(error), file: file, line: line) } - + deinit { if _isDebugAssertConfiguration(), let eventLoop = self.eventLoop as? SelectableEventLoop { let creation = eventLoop.promiseCreationStoreRemove(future: self) @@ -473,7 +473,7 @@ extension EventLoopFuture { } } - + /// When the current `EventLoopFuture` is in an error state, run the provided callback, which /// may recover from the error by returning an `EventLoopFuture`. The callback is intended to potentially /// recover from the error by returning a new `EventLoopFuture` that will eventually contain the recovered @@ -517,7 +517,7 @@ extension EventLoopFuture { return thenIfError { return EventLoopFuture(eventLoop: self.eventLoop, result: callback($0), file: file, line: line) } } - + /// Add a callback. If there's already a value, invoke it and return the resulting list of new callback functions. fileprivate func _addCallback(_ callback: @escaping () -> CallbackList) -> CallbackList { assert(eventLoop.inEventLoop) @@ -527,7 +527,7 @@ extension EventLoopFuture { } return callback() } - + /// Add a callback. If there's already a value, run as much of the chain as we can. fileprivate func _whenComplete(_ callback: @escaping () -> CallbackList) { if eventLoop.inEventLoop { @@ -538,7 +538,7 @@ extension EventLoopFuture { } } } - + fileprivate func _whenCompleteWithValue(_ callback: @escaping (EventLoopFutureValue) -> Void) { _whenComplete { callback(self.value!) @@ -583,7 +583,7 @@ extension EventLoopFuture { return CallbackList() } } - + /// Adds an observer callback to this `EventLoopFuture` that is called when the /// `EventLoopFuture` has any result. /// @@ -600,7 +600,7 @@ extension EventLoopFuture { } } - + /// Internal: Set the value and return a list of callbacks that should be invoked as a result. fileprivate func _setValue(value: EventLoopFutureValue) -> CallbackList { assert(eventLoop.inEventLoop) @@ -625,7 +625,7 @@ extension EventLoopFuture { let promise = EventLoopPromise<(T,U)>(eventLoop: eventLoop, file: file, line: line) var tvalue: T? var uvalue: U? - + _whenComplete { () -> CallbackList in switch self.value! { case .failure(let error): @@ -642,7 +642,7 @@ extension EventLoopFuture { } return CallbackList() } - + other._whenComplete { () -> CallbackList in switch other.value! { case .failure(let error): @@ -659,7 +659,7 @@ extension EventLoopFuture { } return CallbackList() } - + return promise.futureResult } @@ -735,7 +735,7 @@ extension EventLoopFuture { if !(self.eventLoop is EmbeddedEventLoop) { precondition(!eventLoop.inEventLoop, "wait() must not be called when on the EventLoop") } - + var v: EventLoopFutureValue ? = nil let lock = ConditionLock(value: 0) _whenComplete { () -> CallbackList in @@ -746,7 +746,7 @@ extension EventLoopFuture { } lock.lock(whenValue: 1) lock.unlock() - + switch(v!) { case .success(let result): return result diff --git a/Sources/NIO/FileDescriptor.swift b/Sources/NIO/FileDescriptor.swift index 2ffc73797..b9d2c8997 100644 --- a/Sources/NIO/FileDescriptor.swift +++ b/Sources/NIO/FileDescriptor.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// public protocol FileDescriptor { - + /// Will be called with the file descriptor if still open, if not it will /// throw an `IOError`. /// @@ -24,10 +24,10 @@ public protocol FileDescriptor { /// - body: The closure to execute if the `FileDescriptor` is still open. /// - throws: If either the `FileDescriptor` was closed before or the closure throws by itself. func withUnsafeFileDescriptor(_ body: (CInt) throws -> T) throws -> T - + /// `true` if this `FileDescriptor` is open (which means it was not closed yet). var isOpen: Bool { get } - + /// Close this `FileDescriptor`. func close() throws } diff --git a/Sources/NIO/FileHandle.swift b/Sources/NIO/FileHandle.swift index a7ee841b2..1beb55d0f 100644 --- a/Sources/NIO/FileHandle.swift +++ b/Sources/NIO/FileHandle.swift @@ -68,10 +68,10 @@ public final class FileHandle: FileDescriptor { try withUnsafeFileDescriptor { fd in try Posix.close(descriptor: fd) } - + self.isOpen = false } - + public func withUnsafeFileDescriptor(_ body: (CInt) throws -> T) throws -> T { guard self.isOpen else { throw IOError(errnoCode: EBADF, reason: "file descriptor already closed!") diff --git a/Sources/NIO/FileRegion.swift b/Sources/NIO/FileRegion.swift index 5ced6ce0d..9e7e7730b 100644 --- a/Sources/NIO/FileRegion.swift +++ b/Sources/NIO/FileRegion.swift @@ -24,16 +24,16 @@ /// /// - note: It is important to manually manage the lifetime of the `FileHandle` used to create a `FileRegion`. public struct FileRegion { - + /// The `FileHandle` that is used by this `FileRegion`. public let fileHandle: FileHandle - + /// The current reader index of this `FileRegion` private(set) public var readerIndex: Int - + /// The end index of this `FileRegion`. public let endIndex: Int - + /// Create a new `FileRegion` from an open `FileHandle`. /// /// - parameters: @@ -47,12 +47,12 @@ public struct FileRegion { self.readerIndex = readerIndex self.endIndex = endIndex } - + /// The number of readable bytes within this FileRegion (taking the `readerIndex` and `endIndex` into account). public var readableBytes: Int { return endIndex - readerIndex } - + /// Move the readerIndex forward by `offset`. public mutating func moveReaderIndex(forwardBy offset: Int) { let newIndex = self.readerIndex + offset diff --git a/Sources/NIO/IO.swift b/Sources/NIO/IO.swift index c57a65703..dcfa1c92c 100644 --- a/Sources/NIO/IO.swift +++ b/Sources/NIO/IO.swift @@ -23,7 +23,7 @@ public struct IOError: Swift.Error { /// The actual reason (in an human-readable form) for this `IOError`. public let reason: FailureDescription - + /// Creates a new `IOError`` /// /// - note: At the moment, this constructor is more expensive than `IOError(errnoCode:function:)` as the `String` will incur reference counting @@ -84,10 +84,10 @@ extension IOError: CustomStringConvertible { /// An result for an IO operation that was done on a non-blocking resource. public enum IOResult { - + /// Signals that the IO operation could not be completed as otherwise we would need to block. case wouldBlock(T) - + /// Signals that the IO operation was completed. case processed(T) } diff --git a/Sources/NIO/LinuxCPUSet.swift b/Sources/NIO/LinuxCPUSet.swift index 57589f909..367d25c52 100644 --- a/Sources/NIO/LinuxCPUSet.swift +++ b/Sources/NIO/LinuxCPUSet.swift @@ -14,12 +14,12 @@ import CNIOLinux #if os(Linux) - + /// A set that contains CPU ids to use. struct LinuxCPUSet { /// The ids of all the cpus. let cpuIds: Set - + /// Create a new instace /// /// - arguments: @@ -31,7 +31,7 @@ import CNIOLinux } self.cpuIds = cpuIds } - + /// Create a new instance /// /// - arguments: @@ -41,38 +41,38 @@ import CNIOLinux self.init(cpuIds: ids) } } - + extension LinuxCPUSet: Equatable { public static func ==(lhs: LinuxCPUSet, rhs: LinuxCPUSet) -> Bool { return lhs.cpuIds == rhs.cpuIds } } - + /// Linux specific extension to `Thread`. internal extension Thread { /// Specify the thread-affinity of the `Thread` itself. var affinity: LinuxCPUSet { get { var cpuset = cpu_set_t() - + // Ensure the cpuset is empty (and so nothing is selected yet). CNIOLinux_CPU_ZERO(&cpuset) - + let res = withUnsafePthread { p in CNIOLinux_pthread_getaffinity_np(p, MemoryLayout.size(ofValue: cpuset), &cpuset) } - + precondition(res == 0, "pthread_getaffinity_np failed: \(res)") - + let set = Set((CInt(0)..(_ value: T) { self.storage = _NIOAny(value) } - + enum _NIOAny { case ioData(IOData) case bufferEnvelope(AddressedEnvelope) case other(Any) - + init(_ value: T) { switch value { case let value as ByteBuffer: @@ -73,7 +73,7 @@ public struct NIOAny { } } } - + /// Try unwrapping the wrapped message as `ByteBuffer`. /// /// returns: The wrapped `ByteBuffer` or `nil` if the wrapped message is not a `ByteBuffer`. @@ -84,7 +84,7 @@ public struct NIOAny { return nil } } - + /// Force unwrapping the wrapped message as `ByteBuffer`. /// /// returns: The wrapped `ByteBuffer` or crash if the wrapped message is not a `ByteBuffer`. @@ -95,7 +95,7 @@ public struct NIOAny { fatalError("tried to decode as type \(ByteBuffer.self) but found \(Mirror(reflecting: Mirror(reflecting: self.storage).children.first!.value).subjectType)") } } - + /// Try unwrapping the wrapped message as `IOData`. /// /// returns: The wrapped `IOData` or `nil` if the wrapped message is not a `IOData`. @@ -106,7 +106,7 @@ public struct NIOAny { return nil } } - + /// Force unwrapping the wrapped message as `IOData`. /// /// returns: The wrapped `IOData` or crash if the wrapped message is not a `IOData`. @@ -117,7 +117,7 @@ public struct NIOAny { fatalError("tried to decode as type \(IOData.self) but found \(Mirror(reflecting: Mirror(reflecting: self.storage).children.first!.value).subjectType)") } } - + /// Try unwrapping the wrapped message as `FileRegion`. /// /// returns: The wrapped `FileRegion` or `nil` if the wrapped message is not a `FileRegion`. @@ -128,7 +128,7 @@ public struct NIOAny { return nil } } - + /// Force unwrapping the wrapped message as `FileRegion`. /// /// returns: The wrapped `FileRegion` or crash if the wrapped message is not a `FileRegion`. @@ -161,7 +161,7 @@ public struct NIOAny { fatalError("tried to decode as type \(AddressedEnvelope.self) but found \(Mirror(reflecting: Mirror(reflecting: self.storage).children.first!.value).subjectType)") } } - + /// Try unwrapping the wrapped message as `T`. /// /// returns: The wrapped `T` or `nil` if the wrapped message is not a `T`. @@ -172,7 +172,7 @@ public struct NIOAny { return nil } } - + /// Force unwrapping the wrapped message as `T`. /// /// returns: The wrapped `T` or crash if the wrapped message is not a `T`. @@ -183,7 +183,7 @@ public struct NIOAny { fatalError("tried to decode as type \(T.self) but found \(Mirror(reflecting: Mirror(reflecting: self.storage).children.first!.value).subjectType)") } } - + /// Force unwrapping the wrapped message as `T`. /// /// returns: The wrapped `T` or crash if the wrapped message is not a `T`. diff --git a/Sources/NIO/RecvByteBufferAllocator.swift b/Sources/NIO/RecvByteBufferAllocator.swift index 32598c2df..0d5dd3267 100644 --- a/Sources/NIO/RecvByteBufferAllocator.swift +++ b/Sources/NIO/RecvByteBufferAllocator.swift @@ -16,7 +16,7 @@ public protocol RecvByteBufferAllocator { /// Allocates a new `ByteBuffer` that will be used to read bytes from a `Channel`. func buffer(allocator: ByteBufferAllocator) -> ByteBuffer - + /// Records the actual number of bytes that were read by the last socket call. /// /// - parameters: @@ -30,17 +30,17 @@ public protocol RecvByteBufferAllocator { /// `RecvByteBufferAllocator` which will always return a `ByteBuffer` with the same fixed size no matter what was recorded. public struct FixedSizeRecvByteBufferAllocator: RecvByteBufferAllocator { public let capacity: Int - + public init(capacity: Int) { precondition(capacity > 0) self.capacity = capacity } - + public mutating func record(actualReadBytes: Int) -> Bool { // Returns false as we always allocate the same size of buffers. return false } - + public func buffer(allocator: ByteBufferAllocator) -> ByteBuffer { return allocator.buffer(capacity: capacity) } @@ -48,13 +48,13 @@ public struct FixedSizeRecvByteBufferAllocator: RecvByteBufferAllocator { /// `RecvByteBufferAllocator` which will gracefully increment or decrement the buffer size on the feedback that was recorded. public struct AdaptiveRecvByteBufferAllocator: RecvByteBufferAllocator { - + private static let indexIncrement = 4 private static let indexDecrement = 1 - + private static let sizeTable: [Int] = { var sizeTable: [Int] = [] - + var i: Int = 16 while i < 512 { sizeTable.append(i) @@ -66,7 +66,7 @@ public struct AdaptiveRecvByteBufferAllocator: RecvByteBufferAllocator { sizeTable.append(i) i <<= 1 } - + return sizeTable }() @@ -75,11 +75,11 @@ public struct AdaptiveRecvByteBufferAllocator: RecvByteBufferAllocator { public let minimum: Int public let maximum: Int public let initial: Int - + private var index: Int private var nextReceiveBufferSize: Int private var decreaseNow: Bool - + public init() { self.init(minimum: 64, initial: 1024, maximum: 65536) } @@ -88,34 +88,34 @@ public struct AdaptiveRecvByteBufferAllocator: RecvByteBufferAllocator { precondition(minimum >= 0, "minimum: \(minimum)") precondition(initial > minimum, "initial: \(initial)") precondition(maximum > initial, "maximum: \(maximum)") - + let minIndex = AdaptiveRecvByteBufferAllocator.sizeTableIndex(minimum) if AdaptiveRecvByteBufferAllocator.sizeTable[minIndex] < minimum { self.minIndex = minIndex + 1 } else { self.minIndex = minIndex } - + let maxIndex = AdaptiveRecvByteBufferAllocator.sizeTableIndex(maximum) if AdaptiveRecvByteBufferAllocator.sizeTable[maxIndex] > maximum { self.maxIndex = maxIndex - 1 } else { self.maxIndex = maxIndex } - + self.initial = initial self.minimum = minimum self.maximum = maximum - + self.index = AdaptiveRecvByteBufferAllocator.sizeTableIndex(initial) self.nextReceiveBufferSize = AdaptiveRecvByteBufferAllocator.sizeTable[index] self.decreaseNow = false } - + private static func sizeTableIndex(_ size: Int) -> Int { var low: Int = 0 var high: Int = sizeTable.count - 1 - + repeat { if high < low { return low @@ -123,7 +123,7 @@ public struct AdaptiveRecvByteBufferAllocator: RecvByteBufferAllocator { if high == low { return high } - + // Its import to put (...) around as >> is executed before + in swift while in java its the other way around (doh!) let mid = (low + high) >> 1 @@ -141,11 +141,11 @@ public struct AdaptiveRecvByteBufferAllocator: RecvByteBufferAllocator { } } while true } - + public func buffer(allocator: ByteBufferAllocator) -> ByteBuffer { return allocator.buffer(capacity: nextReceiveBufferSize) } - + public mutating func record(actualReadBytes: Int) -> Bool { if actualReadBytes <= AdaptiveRecvByteBufferAllocator.sizeTable[max(0, index - AdaptiveRecvByteBufferAllocator.indexDecrement - 1)] { if decreaseNow { @@ -159,7 +159,7 @@ public struct AdaptiveRecvByteBufferAllocator: RecvByteBufferAllocator { index = min(index + AdaptiveRecvByteBufferAllocator.indexIncrement, maxIndex) nextReceiveBufferSize = AdaptiveRecvByteBufferAllocator.sizeTable[index] decreaseNow = false - + } return actualReadBytes >= nextReceiveBufferSize } diff --git a/Sources/NIO/Resolver.swift b/Sources/NIO/Resolver.swift index 5c26835cc..5fbe16e21 100644 --- a/Sources/NIO/Resolver.swift +++ b/Sources/NIO/Resolver.swift @@ -29,7 +29,7 @@ public protocol Resolver { /// - port: The port we'll be connecting to. /// - returns: An `EventLoopFuture` that fires with the result of the lookup. func initiateAQuery(host: String, port: Int) -> EventLoopFuture<[SocketAddress]> - + /// Initiate a DNS AAAA query for a given host. /// /// - parameters: @@ -37,7 +37,7 @@ public protocol Resolver { /// - port: The port we'll be connecting to. /// - returns: An `EventLoopFuture` that fires with the result of the lookup. func initiateAAAAQuery(host: String, port: Int) -> EventLoopFuture<[SocketAddress]> - + /// Cancel all outstanding DNS queries. /// /// This method is called whenever queries that have not completed no longer have their diff --git a/Sources/NIO/Selector.swift b/Sources/NIO/Selector.swift index 1c452493c..593dbc4fa 100644 --- a/Sources/NIO/Selector.swift +++ b/Sources/NIO/Selector.swift @@ -45,7 +45,7 @@ private extension Optional { /* this is deliberately not thread-safe, only the wakeup() function may be called unprotectedly */ final class Selector { private var lifecycleState: SelectorLifecycleState - + #if os(Linux) private typealias EventType = Epoll.epoll_event private let eventfd: Int32 @@ -58,29 +58,29 @@ final class Selector { private var eventsCapacity = 64 private var events: UnsafeMutablePointer private var registrations = [Int: R]() - + private static func allocateEventsArray(capacity: Int) -> UnsafeMutablePointer { let events: UnsafeMutablePointer = UnsafeMutablePointer.allocate(capacity: capacity) events.initialize(to: EventType()) return events } - + private static func deallocateEventsArray(events: UnsafeMutablePointer, capacity: Int) { events.deinitialize(count: capacity) events.deallocate() } - + private func growEventArrayIfNeeded(ready: Int) { guard ready == eventsCapacity else { return } Selector.deallocateEventsArray(events: events, capacity: eventsCapacity) - + // double capacity eventsCapacity = ready << 1 events = Selector.allocateEventsArray(capacity: eventsCapacity) } - + init() throws { events = Selector.allocateEventsArray(capacity: eventsCapacity) self.lifecycleState = .closed @@ -89,7 +89,7 @@ final class Selector { fd = try Epoll.epoll_create(size: 128) eventfd = try EventFd.eventfd(initval: 0, flags: Int32(EventFd.EFD_CLOEXEC | EventFd.EFD_NONBLOCK)) timerfd = try TimerFd.timerfd_create(clockId: CLOCK_MONOTONIC, flags: Int32(TimerFd.TFD_CLOEXEC | TimerFd.TFD_NONBLOCK)) - + self.lifecycleState = .open var ev = Epoll.epoll_event() @@ -97,7 +97,7 @@ final class Selector { ev.data.fd = eventfd _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_ADD, fd: eventfd, event: &ev) - + var timerev = Epoll.epoll_event() timerev.events = Epoll.EPOLLIN.rawValue | Epoll.EPOLLERR.rawValue | Epoll.EPOLLRDHUP.rawValue | Epoll.EPOLLET.rawValue timerev.data.fd = timerfd @@ -105,7 +105,7 @@ final class Selector { #else fd = try KQueue.kqueue() self.lifecycleState = .open - + var event = kevent() event.ident = 0 event.filter = Int16(EVFILT_USER) @@ -180,13 +180,13 @@ final class Selector { // Allocated on the stack var events = (kevent(), kevent()) try selectable.withUnsafeFileDescriptor { fd in - + events.0.ident = UInt(fd) events.0.filter = Int16(EVFILT_READ) events.0.fflags = 0 events.0.data = 0 events.0.udata = nil - + events.1.ident = UInt(fd) events.1.filter = Int16(EVFILT_WRITE) events.1.fflags = 0 @@ -268,14 +268,14 @@ final class Selector { guard self.lifecycleState == .open else { throw IOError(errnoCode: EBADF, reason: "can't register on selector as it's \(self.lifecycleState).") } - + try selectable.withUnsafeFileDescriptor { fd in assert(registrations[Int(fd)] == nil) #if os(Linux) var ev = Epoll.epoll_event() ev.events = Selector.toEpollEvents(interested: interested) ev.data.fd = fd - + _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_ADD, fd: fd, event: &ev) #else try register_kqueue(selectable: selectable, interested: interested, oldInterested: nil) @@ -295,12 +295,12 @@ final class Selector { } try selectable.withUnsafeFileDescriptor { fd in var reg = registrations[Int(fd)]! - + #if os(Linux) var ev = Epoll.epoll_event() ev.events = Selector.toEpollEvents(interested: interested) ev.data.fd = fd - + _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_MOD, fd: fd, event: &ev) #else try register_kqueue(selectable: selectable, interested: interested, oldInterested: reg.interested) @@ -309,7 +309,7 @@ final class Selector { registrations[Int(fd)] = reg } } - + /// Deregister `Selectable`, must be registered via `register` before. /// /// After the `Selectable is deregistered no `IOEvent`s will be produced anymore for the `Selectable`. @@ -324,7 +324,7 @@ final class Selector { guard let reg = registrations.removeValue(forKey: Int(fd)) else { return } - + #if os(Linux) var ev = Epoll.epoll_event() _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_DEL, fd: fd, event: &ev) @@ -346,7 +346,7 @@ final class Selector { #if os(Linux) let ready: Int - + switch strategy { case .now: ready = Int(try Epoll.epoll_wait(epfd: self.fd, events: events, maxevents: Int32(eventsCapacity), timeout: 0)) @@ -358,7 +358,7 @@ final class Selector { case .block: ready = Int(try Epoll.epoll_wait(epfd: self.fd, events: events, maxevents: Int32(eventsCapacity), timeout: -1)) } - + for i in 0.. { registration: registration)) } } - + growEventArrayIfNeeded(ready: ready) #else let timespec = toKQueueTimeSpec(strategy: strategy) let ready = try timespec.withUnsafeOptionalPointer { ts in Int(try KQueue.kevent(kq: self.fd, changelist: nil, nchanges: 0, eventlist: events, nevents: Int32(eventsCapacity), timeout: ts)) } - + for i in 0.. { fatalError("unexpected filter \(ev.filter)") } } - + growEventArrayIfNeeded(ready: ready) #endif } @@ -463,7 +463,7 @@ extension Selector: CustomStringConvertible { struct SelectorEvent { public let registration: R public let io: IOEvent - + /// Create new instance /// /// - parameters: @@ -519,7 +519,7 @@ enum SelectorStrategy { /// Block until there is some IO ready to be processed, the `Selector` is explictly woken up or the given `TimeAmount` elapsed. case blockUntilTimeout(TimeAmount) - + /// Try to select all ready IO at this point in time without blocking at all. case now } @@ -528,13 +528,13 @@ enum SelectorStrategy { public enum IOEvent { /// Something is ready to be read. case read - + /// Its possible to write some data again. case write - + /// Combination of `read` and `write`. case all - + /// Not interested in any event. case none } diff --git a/Sources/NIO/ServerSocket.swift b/Sources/NIO/ServerSocket.swift index 9f6e46140..96f6a0020 100644 --- a/Sources/NIO/ServerSocket.swift +++ b/Sources/NIO/ServerSocket.swift @@ -20,7 +20,7 @@ final class ServerSocket: BaseSocket { try socket.listen() return socket } - + /// Create a new instance. /// /// - parameters: @@ -30,7 +30,7 @@ final class ServerSocket: BaseSocket { let sock = try BaseSocket.newSocket(protocolFamily: protocolFamily, type: Posix.SOCK_STREAM) super.init(descriptor: sock) } - + /// Start to listen for new connections. /// /// - parameters: @@ -41,7 +41,7 @@ final class ServerSocket: BaseSocket { _ = try Posix.listen(descriptor: fd, backlog: backlog) } } - + /// Accept a new connection /// /// - returns: A `Socket` once a new connection was established or `nil` if this `ServerSocket` is in non-blocking mode and there is no new connection that can be accepted when this method is called. @@ -50,13 +50,13 @@ final class ServerSocket: BaseSocket { return try withUnsafeFileDescriptor { fd in var acceptAddr = sockaddr_in() var addrSize = socklen_t(MemoryLayout.size) - + let result = try withUnsafeMutablePointer(to: &acceptAddr) { ptr in try ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { ptr in try Posix.accept(descriptor: fd, addr: ptr, len: &addrSize) } } - + guard let fd = result else { return nil } diff --git a/Sources/NIO/Socket.swift b/Sources/NIO/Socket.swift index b9eecdb1e..19f897af0 100644 --- a/Sources/NIO/Socket.swift +++ b/Sources/NIO/Socket.swift @@ -22,7 +22,7 @@ final class Socket: BaseSocket { static var writevLimitBytes: Int { return Int(Int32.max) } - + /// The maximum number of `IOVector`s to write per `writev` call. static let writevLimitIOVectors: Int = Posix.UIO_MAXIOV @@ -36,7 +36,7 @@ final class Socket: BaseSocket { let sock = try BaseSocket.newSocket(protocolFamily: protocolFamily, type: type) super.init(descriptor: sock) } - + /// Create a new instance. /// /// The ownership of the passed in descriptor is transferred to this class. A user must call `close` to close the underlying @@ -47,7 +47,7 @@ final class Socket: BaseSocket { override init(descriptor: Int32) { super.init(descriptor: descriptor) } - + /// Connect to the `SocketAddress`. /// /// - parameters: @@ -64,7 +64,7 @@ final class Socket: BaseSocket { return try connectSocket(addr: addr.address) } } - + /// Private helper function to handle connection attempts. private func connectSocket(addr: T) throws -> Bool { return try withUnsafeFileDescriptor { fd in @@ -76,7 +76,7 @@ final class Socket: BaseSocket { } } } - + /// Finish a previous non-blocking `connect` operation. /// /// - throws: An `IOError` if the operation failed. @@ -86,7 +86,7 @@ final class Socket: BaseSocket { throw IOError(errnoCode: result, function: "getsockopt") } } - + /// Write data to the remote peer. /// /// - parameters: @@ -125,7 +125,7 @@ final class Socket: BaseSocket { try Posix.sendto(descriptor: fd, pointer: UnsafeMutablePointer(mutating: pointer), size: size, destinationPtr: destinationPtr, destinationSize: destinationSize) } } - + /// Read data from the socket. /// /// - parameters: @@ -155,7 +155,7 @@ final class Socket: BaseSocket { } } } - + /// Send the content of a file descriptor to the remote peer (if possible a zero-copy strategy is applied). /// /// - parameters: @@ -193,7 +193,7 @@ final class Socket: BaseSocket { try Posix.sendmmsg(sockfd: fd, msgvec: msgs.baseAddress!, vlen: CUnsignedInt(msgs.count), flags: 0) } } - + /// Shutdown the socket. /// /// - parameters: diff --git a/Sources/NIO/SocketAddresses.swift b/Sources/NIO/SocketAddresses.swift index 4b83e18c1..d39abfb34 100644 --- a/Sources/NIO/SocketAddresses.swift +++ b/Sources/NIO/SocketAddresses.swift @@ -26,7 +26,7 @@ public enum SocketAddressError: Error { /// Represent a socket address to which we may want to connect or bind. public enum SocketAddress: CustomStringConvertible { - + /// A single IPv4 address for `SocketAddress`. public struct IPv4Address { private let _storage: Box<(address: sockaddr_in, host: String)> @@ -98,7 +98,7 @@ public enum SocketAddress: CustomStringConvertible { } return "[\(type)]\(host.map { "\($0):" } ?? "")\(port)" } - + /// Returns the protocol family as defined in `man 2 socket` of this `SocketAddress`. public var protocolFamily: Int32 { switch self { @@ -232,18 +232,18 @@ public enum SocketAddress: CustomStringConvertible { /// - throws: a `SocketAddressError.unknown` if we could not resolve the `host`, or `SocketAddressError.unsupported` if the address itself is not supported (yet). public static func newAddressResolving(host: String, port: Int) throws -> SocketAddress { var info: UnsafeMutablePointer? - + /* FIXME: this is blocking! */ if getaddrinfo(host, String(port), nil, &info) != 0 { throw SocketAddressError.unknown(host: host, port: port) } - + defer { if info != nil { freeaddrinfo(info) } } - + if let info = info { switch info.pointee.ai_family { case AF_INET: diff --git a/Sources/NIO/SocketChannel.swift b/Sources/NIO/SocketChannel.swift index b2221d937..5909a05a5 100644 --- a/Sources/NIO/SocketChannel.swift +++ b/Sources/NIO/SocketChannel.swift @@ -598,7 +598,7 @@ class BaseSocketChannel: SelectableChannel, ChannelCore { // Call before triggering the close of the Channel. pipeline.fireChannelReadComplete0() close0(error: err, mode: .all, promise: nil) - + return } pipeline.fireChannelReadComplete0() diff --git a/Sources/NIO/System.swift b/Sources/NIO/System.swift index 9f1e179c7..f711f169c 100644 --- a/Sources/NIO/System.swift +++ b/Sources/NIO/System.swift @@ -93,7 +93,7 @@ internal func wrapSyscallMayBlock(where function: StaticSt assert(!isBlacklistedErrno(err), "blacklisted errno \(err) \(strerror(err)!)") throw IOError(errnoCode: err, function: function) } - + } return .processed(res) } @@ -137,7 +137,7 @@ enum Shutdown { case RD case WR case RDWR - + fileprivate var cValue: CInt { switch self { case .RD: @@ -170,32 +170,32 @@ internal enum Posix { fatalError("unsupported OS") } #endif - + static let AF_INET = sa_family_t(sysAF_INET) static let AF_INET6 = sa_family_t(sysAF_INET6) static let AF_UNIX = sa_family_t(sysAF_UNIX) - + @inline(never) public static func shutdown(descriptor: CInt, how: Shutdown) throws { _ = try wrapSyscall { sysShutdown(descriptor, how.cValue) } } - + @inline(never) public static func close(descriptor: CInt) throws { _ = try wrapSyscall { sysClose(descriptor) } } - + @inline(never) public static func bind(descriptor: CInt, ptr: UnsafePointer, bytes: Int) throws { _ = try wrapSyscall { sysBind(descriptor, ptr, socklen_t(bytes)) } } - + @inline(never) // TODO: Allow varargs public static func fcntl(descriptor: CInt, command: CInt, value: CInt) throws { @@ -203,7 +203,7 @@ internal enum Posix { sysFcntl(descriptor, command, value) } } - + @inline(never) public static func socket(domain: CInt, type: CInt, `protocol`: CInt) throws -> CInt { return try wrapSyscall { @@ -220,7 +220,7 @@ internal enum Posix { return fd } } - + @inline(never) public static func setsockopt(socket: CInt, level: CInt, optionName: CInt, optionValue: UnsafeRawPointer, optionLen: socklen_t) throws { @@ -228,7 +228,7 @@ internal enum Posix { sysSetsockopt(socket, level, optionName, optionValue, optionLen) } } - + @inline(never) public static func getsockopt(socket: CInt, level: CInt, optionName: CInt, optionValue: UnsafeMutableRawPointer, optionLen: UnsafeMutablePointer) throws { @@ -243,7 +243,7 @@ internal enum Posix { sysListen(descriptor, backlog) } } - + @inline(never) public static func accept(descriptor: CInt, addr: UnsafeMutablePointer, len: UnsafeMutablePointer) throws -> CInt? { let result: IOResult = try wrapSyscallMayBlock { @@ -257,7 +257,7 @@ internal enum Posix { #endif return fd } - + switch result { case .processed(let fd): return fd @@ -265,7 +265,7 @@ internal enum Posix { return nil } } - + @inline(never) public static func connect(descriptor: CInt, addr: UnsafePointer, size: socklen_t) throws -> Bool { do { @@ -280,7 +280,7 @@ internal enum Posix { throw err } } - + @inline(never) public static func open(file: UnsafePointer, oFlag: CInt, mode: mode_t) throws -> CInt { return try wrapSyscall { @@ -294,14 +294,14 @@ internal enum Posix { sysOpen(file, oFlag) } } - + @inline(never) public static func write(descriptor: CInt, pointer: UnsafePointer, size: Int) throws -> IOResult { return try wrapSyscallMayBlock { sysWrite(descriptor, pointer, size) } } - + @inline(never) public static func writev(descriptor: CInt, iovecs: UnsafeBufferPointer) throws -> IOResult { return try wrapSyscallMayBlock { @@ -427,7 +427,7 @@ internal enum KQueue { Darwin.kqueue() } } - + @inline(never) public static func kevent(kq: CInt, changelist: UnsafePointer?, nchanges: CInt, eventlist: UnsafeMutablePointer?, nevents: CInt, timeout: UnsafePointer?) throws -> CInt { return try wrapSyscall { diff --git a/Sources/NIO/Thread.swift b/Sources/NIO/Thread.swift index b8cd04bb9..50dc936b9 100644 --- a/Sources/NIO/Thread.swift +++ b/Sources/NIO/Thread.swift @@ -36,10 +36,10 @@ private func sys_pthread_setname_np(_ p: pthread_t, _ pointer: UnsafePointer(_ body: (pthread_t) throws -> T) rethrows -> T { return try body(self.pthread) } - + /// Get current name of the `Thread` or `nil` if not set. var name: String? { get { @@ -70,7 +70,7 @@ final class Thread { return String(cString: chars) } } - + /// Spawns and runs some task in a `Thread`. /// /// - arguments: @@ -83,19 +83,19 @@ final class Thread { #else var pt: pthread_t? = nil #endif - + // Store everything we want to pass into the c function in a Box so we can hand-over the reference. let tuple: ThreadBoxValue = (body: body, name: name) let box = ThreadBox(tuple) let res = pthread_create(&pt, nil, { p in // Cast to UnsafeMutableRawPointer? and force unwrap to make the same code work on macOS and Linux. let b = Unmanaged.fromOpaque((p as UnsafeMutableRawPointer?)!.assumingMemoryBound(to: ThreadBox.self)).takeRetainedValue() - + let body = b.value.body let name = b.value.name - + let pt = pthread_self() - + if let threadName = name { let res = sys_pthread_setname_np(pt, threadName) // This should only happen in case of a too-long name. @@ -105,18 +105,18 @@ final class Thread { body(Thread(pthread: pt)) return nil }, Unmanaged.passRetained(box).toOpaque()) - + precondition(res == 0, "Unable to create thread: \(res)") let detachError = pthread_detach((pt as pthread_t?)!) precondition(detachError == 0, "pthread_detach failed with error \(detachError)") } - + /// Returns `true` if the calling thread is the same as this one. var isCurrent: Bool { return pthread_equal(pthread, pthread_self()) != 0 } - + /// Returns the current running `Thread`. static var current: Thread { return Thread(pthread: pthread_self()) diff --git a/Sources/NIO/TypeAssistedChannelHandler.swift b/Sources/NIO/TypeAssistedChannelHandler.swift index e2d930ad3..e2de88541 100644 --- a/Sources/NIO/TypeAssistedChannelHandler.swift +++ b/Sources/NIO/TypeAssistedChannelHandler.swift @@ -18,7 +18,7 @@ public protocol _EmittingChannelHandler { /// The type of the outbound data which will be forwarded to the next `ChannelOutboundHandler` in the `ChannelPipeline`. associatedtype OutboundOut = Never - + /// Wrap the provided `OutboundOut` that will be passed to the next `ChannelOutboundHandler` by calling `ChannelHandlerContext.write`. func wrapOutboundOut(_ value: OutboundOut) -> NIOAny } @@ -36,13 +36,13 @@ extension _EmittingChannelHandler { public protocol ChannelInboundHandler: _ChannelInboundHandler, _EmittingChannelHandler { /// The type of the inbound data which is wrapped in `NIOAny`. associatedtype InboundIn - + /// The type of the inbound data which will be forwarded to the next `ChannelInboundHandler` in the `ChannelPipeline`. associatedtype InboundOut = Never /// Unwrap the provided `NIOAny` that was passed to `channelRead`. func unwrapInboundIn(_ value: NIOAny) -> InboundIn - + /// Wrap the provided `InboundOut` that will be passed to the next `ChannelInboundHandler` by calling `ChannelHandlerContext.fireChannelRead`. func wrapInboundOut(_ value: InboundOut) -> NIOAny } diff --git a/Sources/NIOChatClient/main.swift b/Sources/NIOChatClient/main.swift index 78da65d3e..502b0f6fc 100644 --- a/Sources/NIOChatClient/main.swift +++ b/Sources/NIOChatClient/main.swift @@ -16,7 +16,7 @@ import NIO private final class ChatHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer - + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { var buffer = self.unwrapInboundIn(data) while let byte: UInt8 = buffer.readInteger() { diff --git a/Sources/NIOChatServer/main.swift b/Sources/NIOChatServer/main.swift index 6d141e625..35f8d4af5 100644 --- a/Sources/NIOChatServer/main.swift +++ b/Sources/NIOChatServer/main.swift @@ -22,7 +22,7 @@ final class LineDelimiterCodec: ByteToMessageDecoder { public typealias InboundOut = ByteBuffer public var cumulationBuffer: ByteBuffer? - + public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { let readable = buffer.withUnsafeReadableBytes { $0.index(of: newLine) } if let r = readable { @@ -46,15 +46,15 @@ final class LineDelimiterCodec: ByteToMessageDecoder { final class ChatHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer - + // All access to channels is guarded by channelsSyncQueue. private let channelsSyncQueue = DispatchQueue(label: "channelsQueue") private var channels: [ObjectIdentifier: Channel] = [:] - + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { let id = ObjectIdentifier(ctx.channel) var read = self.unwrapInboundIn(data) - + // 64 should be good enough for the ipaddress var buffer = ctx.channel.allocator.buffer(capacity: read.readableBytes + 64) buffer.write(string: "(\(ctx.channel.remoteAddress!)) - ") @@ -64,22 +64,22 @@ final class ChatHandler: ChannelInboundHandler { self.writeToAll(channels: self.channels.filter { id != $0.key }, buffer: buffer) } } - + public func errorCaught(ctx: ChannelHandlerContext, error: Error) { print("error: ", error) - + // As we are not really interested getting notified on success or failure we just pass nil as promise to // reduce allocations. ctx.close(promise: nil) } - + public func channelActive(ctx: ChannelHandlerContext) { let remoteAddress = ctx.remoteAddress! let channel = ctx.channel self.channelsSyncQueue.async { // broadcast the message to all the connected clients except the one that just became active. self.writeToAll(channels: self.channels, allocator: channel.allocator, message: "(ChatServer) - New client connected with address: \(remoteAddress)\n") - + self.channels[ObjectIdentifier(channel)] = channel } @@ -87,7 +87,7 @@ final class ChatHandler: ChannelInboundHandler { buffer.write(string: "(ChatServer) - Welcome to: \(ctx.localAddress!)\n") ctx.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) } - + public func channelInactive(ctx: ChannelHandlerContext) { let channel = ctx.channel self.channelsSyncQueue.async { @@ -97,13 +97,13 @@ final class ChatHandler: ChannelInboundHandler { } } } - + private func writeToAll(channels: [ObjectIdentifier: Channel], allocator: ByteBufferAllocator, message: String) { var buffer = allocator.buffer(capacity: message.utf8.count) buffer.write(string: message) self.writeToAll(channels: channels, buffer: buffer) } - + private func writeToAll(channels: [ObjectIdentifier: Channel], buffer: ByteBuffer) { channels.forEach { $0.value.writeAndFlush(buffer, promise: nil) } } @@ -117,7 +117,7 @@ let bootstrap = ServerBootstrap(group: group) // Specify backlog and enable SO_REUSEADDR for the server itself .serverChannelOption(ChannelOptions.backlog, value: 256) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) - + // Set the handlers that are appled to the accepted Channels .childChannelInitializer { channel in // Add handler that will buffer data until a \n is received @@ -126,7 +126,7 @@ let bootstrap = ServerBootstrap(group: group) channel.pipeline.add(handler: chatHandler) } } - + // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1) .childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) diff --git a/Sources/NIOEchoClient/main.swift b/Sources/NIOEchoClient/main.swift index 49ec0c188..1eec27704 100644 --- a/Sources/NIOEchoClient/main.swift +++ b/Sources/NIOEchoClient/main.swift @@ -20,12 +20,12 @@ private final class EchoHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer private var numBytes = 0 - + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { numBytes -= self.unwrapInboundIn(data).readableBytes assert(numBytes >= 0) - + if numBytes == 0 { print("Received the line back from the server, closing channel") ctx.close(promise: nil) @@ -39,10 +39,10 @@ private final class EchoHandler: ChannelInboundHandler { // reduce allocations. ctx.close(promise: nil) } - + public func channelActive(ctx: ChannelHandlerContext) { print("Client connected to \(ctx.remoteAddress!)") - + // We are connected its time to send the message to the server to initialize the ping-pong sequence. var buffer = ctx.channel.allocator.buffer(capacity: line.utf8.count) buffer.write(string: line) diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index ebf6c02d3..040a3f24a 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -25,7 +25,7 @@ private struct HTTPParserState { var readerIndexAdjustment = 0 // This is set before http_parser_execute(...) is called and set to nil again after it finish var baseAddress: UnsafePointer? - + enum DataAwaitingState { case messageBegin case status @@ -52,7 +52,7 @@ private struct HTTPParserState { self.slice = nil return string } - + mutating func complete(state: DataAwaitingState) { switch state { case .messageBegin: @@ -232,13 +232,13 @@ public final class HTTPResponseDecoder: HTTPDecoder, Cha public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { public typealias InboundIn = ByteBuffer public typealias InboundOut = HTTPMessageT - + private var parser = http_parser() private var settings = http_parser_settings() - + fileprivate var pendingCallouts: [() -> Void] = [] fileprivate var state = HTTPParserState() - + fileprivate init(type: HTTPMessageT.Type) { /* this is a private init, the public versions only allow HTTPClientResponsePart and HTTPServerRequestPart */ assert(HTTPMessageT.self == HTTPClientResponsePart.self || HTTPMessageT.self == HTTPServerRequestPart.self) @@ -248,7 +248,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { /// /// Naturally, in the base case this returns nil, as servers never issue requests! fileprivate func popRequestMethod() -> HTTPMethod? { return nil } - + private func newRequestHead(_ parser: UnsafeMutablePointer!) -> HTTPRequestHead { let method = HTTPMethod.from(httpParserMethod: http_method(rawValue: parser.pointee.method)) let version = HTTPVersion(major: parser.pointee.http_major, minor: parser.pointee.http_minor) @@ -256,7 +256,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { state.currentHeaders = nil return request } - + private func newResponseHead(_ parser: UnsafeMutablePointer!) -> HTTPResponseHead { let status = HTTPResponseStatus.from(parser.pointee.status_code, state.currentStatus!) let version = HTTPVersion(major: parser.pointee.http_major, minor: parser.pointee.http_minor) @@ -264,7 +264,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { state.currentHeaders = nil return response } - + public func decoderAdded(ctx: ChannelHandlerContext) { if HTTPMessageT.self == HTTPServerRequestPart.self { c_nio_http_parser_init(&parser, HTTP_REQUEST) @@ -326,10 +326,10 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { let ctx = evacuateChannelHandlerContext(parser) let handler = evacuateHTTPDecoder(parser) assert(handler.state.dataAwaitingState == .body) - + // Calculate the index of the data in the cumulationBuffer so we can slice out the ByteBuffer without doing any memory copy let index = handler.state.calculateIndex(data: data!, length: len) - + let slice = handler.state.cumulationBuffer!.getSlice(at: index, length: len)! handler.pendingCallouts.append { switch handler { @@ -341,7 +341,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { fatalError("the impossible happened: handler neither a HTTPRequestDecoder nor a HTTPResponseDecoder which should be impossible") } } - + return 0 } @@ -373,7 +373,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { } return 0 } - + settings.on_url = { parser, data, len in let handler = evacuateHTTPDecoder(parser) assert(handler is HTTPRequestDecoder) @@ -410,7 +410,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { public func decoderRemoved(ctx: ChannelHandlerContext) { // Remove the stored reference to ChannelHandlerContext parser.data = UnsafeMutableRawPointer(bitPattern: 0x0000deadbeef0000) - + // Set the callbacks to nil as we dont need these anymore settings.on_body = nil settings.on_chunk_complete = nil @@ -422,7 +422,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { settings.on_header_value = nil settings.on_message_begin = nil } - + public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = state.slice { // If we stored a slice before we need to ensure we move the readerIndex so we don't try to parse the data again. We @@ -430,16 +430,16 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { state.slice = (buffer.readerIndex, slice.length) buffer.moveReaderIndex(forwardBy: state.readerIndexAdjustment) } - + let result = try buffer.withVeryUnsafeBytes { (pointer) -> size_t in state.baseAddress = pointer.baseAddress!.assumingMemoryBound(to: UInt8.self) - + let result = state.baseAddress!.withMemoryRebound(to: Int8.self, capacity: pointer.count, { p in c_nio_http_parser_execute(&parser, &settings, p.advanced(by: buffer.readerIndex), buffer.readableBytes) }) - + state.baseAddress = nil - + let errno = parser.http_errno if errno != 0 { throw HTTPParserError.httpError(fromCHTTPParserErrno: http_errno(rawValue: errno))! @@ -462,7 +462,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { return .continue } } - + public func channelReadComplete(ctx: ChannelHandlerContext) { /* call all the callbacks generated while parsing */ let pending = self.pendingCallouts diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index 2ff1230ea..f7b7592dd 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -16,7 +16,7 @@ import NIO private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandlerContext, isChunked: Bool, chunk: IOData, promise: EventLoopPromise?) { let (mW1, mW2, mW3): (EventLoopPromise<()>?, EventLoopPromise<()>?, EventLoopPromise<()>?) - + switch (isChunked, promise) { case (true, .some(let p)): /* chunked encoding and the user's interested: we need three promises and need to cascade into the users promise */ @@ -30,9 +30,9 @@ private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandler /* user isn't interested, let's not bother even allocating promises */ (mW1, mW2, mW3) = (nil, nil, nil) } - + let readableBytes = chunk.readableBytes - + /* we don't want to copy the chunk unnecessarily and therefore call write an annoyingly large number of times */ if isChunked { var buffer = ctx.channel.allocator.buffer(capacity: 32) @@ -40,9 +40,9 @@ private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandler buffer.write(string: len) buffer.write(staticString: "\r\n") ctx.write(wrapOutboundOut(.byteBuffer(buffer)), promise: mW1) - + ctx.write(wrapOutboundOut(chunk), promise: mW2) - + // Just move the buffers readerIndex to only make the \r\n readable and depend on COW semantics. buffer.moveReaderIndex(forwardBy: buffer.readableBytes - 2) ctx.write(wrapOutboundOut(.byteBuffer(buffer)), promise: mW3) @@ -75,7 +75,7 @@ private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHand } private func writeHead(wrapOutboundOut: (IOData) -> NIOAny, writeStartLine: (inout ByteBuffer) -> Void, ctx: ChannelHandlerContext, headers: HTTPHeaders, promise: EventLoopPromise?) { - + var buffer = ctx.channel.allocator.buffer(capacity: 256) writeStartLine(&buffer) headers.write(buffer: &buffer) @@ -115,18 +115,18 @@ private func sanitizeTransportHeaders(hasBody: HTTPMethod.HasBody, headers: inou public final class HTTPRequestEncoder: ChannelOutboundHandler { public typealias OutboundIn = HTTPClientRequestPart public typealias OutboundOut = IOData - + private var isChunked = false - + public init () { } - + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { switch self.unwrapOutboundIn(data) { case .head(var request): sanitizeTransportHeaders(hasBody: request.method.hasRequestBody, headers: &request.headers, version: request.version) self.isChunked = isChunkedPart(request.headers) - + writeHead(wrapOutboundOut: self.wrapOutboundOut, writeStartLine: { buffer in request.method.write(buffer: &buffer) buffer.write(staticString: " ") @@ -159,7 +159,7 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler { switch self.unwrapOutboundIn(data) { case .head(var response): sanitizeTransportHeaders(hasBody: response.status.mayHaveResponseBody ? .yes : .no, headers: &response.headers, version: response.version) - + self.isChunked = isChunkedPart(response.headers) writeHead(wrapOutboundOut: self.wrapOutboundOut, writeStartLine: { buffer in response.version.write(buffer: &buffer) diff --git a/Sources/NIOHTTP1/HTTPResponseCompressor.swift b/Sources/NIOHTTP1/HTTPResponseCompressor.swift index 746de9af1..9adbe12b2 100644 --- a/Sources/NIOHTTP1/HTTPResponseCompressor.swift +++ b/Sources/NIOHTTP1/HTTPResponseCompressor.swift @@ -184,7 +184,7 @@ public final class HTTPResponseCompressor: ChannnelDuplexHandler { // the client has expressed a preference. return .gzip } - + return nil } diff --git a/Sources/NIOHTTP1/HTTPTypes.swift b/Sources/NIOHTTP1/HTTPTypes.swift index 542c6faac..48ef458b0 100644 --- a/Sources/NIOHTTP1/HTTPTypes.swift +++ b/Sources/NIOHTTP1/HTTPTypes.swift @@ -139,7 +139,7 @@ public struct HTTPResponseHead: Equatable { self.status = status self.headers = headers } - + public static func ==(lhs: HTTPResponseHead, rhs: HTTPResponseHead) -> Bool { return lhs.status == rhs.status && lhs.version == rhs.version && lhs.headers == rhs.headers } @@ -388,7 +388,7 @@ public enum HTTPMethod: Equatable { case no case unlikely } - + public static func ==(lhs: HTTPMethod, rhs: HTTPMethod) -> Bool { switch (lhs, rhs){ case (.GET, .GET): diff --git a/Sources/NIOPriorityQueue/Heap.swift b/Sources/NIOPriorityQueue/Heap.swift index 12da162f8..836f01508 100644 --- a/Sources/NIOPriorityQueue/Heap.swift +++ b/Sources/NIOPriorityQueue/Heap.swift @@ -21,7 +21,7 @@ import Glibc public enum HeapType { case maxHeap case minHeap - + public func comparator(type: T.Type) -> (T, T) -> Bool { switch self { case .maxHeap: @@ -36,7 +36,7 @@ internal struct Heap { internal let type: HeapType internal private(set) var storage: ContiguousArray = [] private let comparator: (T, T) -> Bool - + internal init?(type: HeapType, storage: ContiguousArray) { self.comparator = type.comparator(type: T.self) self.storage = storage @@ -50,7 +50,7 @@ internal struct Heap { self.comparator = type.comparator(type: T.self) self.type = type } - + // MARK: verbatim from CLRS's (Introduction to Algorithms) Heapsort chapter with the following changes // - added a `compare` parameter to make it either a min or a max heap // - renamed `largest` to `root` @@ -66,34 +66,34 @@ internal struct Heap { private static func leftIndex(_ i: Int) -> Int { return 2*i + 1 } - + // named `RIGHT` in CLRS private static func rightIndex(_ i: Int) -> Int { return 2*i + 2 } - + // named `MAX-HEAPIFY` in CLRS private static func heapify(storage: inout ContiguousArray, compare: (T, T) -> Bool, _ i: Int) { let l = Heap.leftIndex(i) let r = Heap.rightIndex(i) - + var root: Int if l <= (storage.count - 1) && compare(storage[l], storage[i]) { root = l } else { root = i } - + if r <= (storage.count - 1) && compare(storage[r], storage[root]) { root = r } - + if root != i { storage.swapAt(i, root) heapify(storage: &storage, compare: compare, root) } } - + // named `MAX-HEAP-INSERT` in CRLS private static func heapInsert(storage: inout ContiguousArray, compare: (T, T) -> Bool, key: T) { var i = storage.count @@ -103,7 +103,7 @@ internal struct Heap { i = parentIndex(i) } } - + // named `HEAP-INCREASE-KEY` in CRLS private static func heapRootify(storage: inout ContiguousArray, compare: (T, T) -> Bool, index: Int, key: T) { var index = index @@ -122,11 +122,11 @@ internal struct Heap { public mutating func append(_ value: T) { Heap.heapInsert(storage: &self.storage, compare: self.comparator, key: value) } - + public mutating func removeRoot() -> T? { return self.remove(index: 0) } - + public mutating func remove(value: T) -> Bool { if let idx = self.storage.index(of: value) { _ = self.remove(index: idx) @@ -135,7 +135,7 @@ internal struct Heap { return false } } - + private mutating func remove(index: Int) -> T? { guard self.storage.count > 0 else { return nil @@ -197,7 +197,7 @@ extension Heap: CustomDebugStringConvertible { } return desc } - + var all = "\n" let spacing = String(repeating: " ", count: maxLen) func subtreeWidths(rootIndex: Int) -> (Int, Int) { @@ -220,7 +220,7 @@ extension Heap: CustomDebugStringConvertible { all += String(repeating: " ", count: leftWidth) all += desc all += String(repeating: " ", count: rightWidth) - + func height(index: Int) -> Int { return Int(log2(Double(index + 1))) } diff --git a/Sources/NIOPriorityQueue/PriorityQueue.swift b/Sources/NIOPriorityQueue/PriorityQueue.swift index 80308892e..bcf05dce5 100644 --- a/Sources/NIOPriorityQueue/PriorityQueue.swift +++ b/Sources/NIOPriorityQueue/PriorityQueue.swift @@ -14,33 +14,33 @@ public struct PriorityQueue { private var heap: Heap - + public init(ascending: Bool = false) { self.heap = Heap(type: ascending ? .minHeap : .maxHeap) } - + public mutating func remove(_ key: T) { assert(self.heap.checkHeapProperty(), "broken heap: \(self.heap.debugDescription)") _ = self.heap.remove(value: key) assert(self.heap.checkHeapProperty(), "broken heap: \(self.heap.debugDescription)") } - + public mutating func push(_ key: T) { assert(self.heap.checkHeapProperty(), "broken heap: \(self.heap.debugDescription)") self.heap.append(key) assert(self.heap.checkHeapProperty(), "broken heap: \(self.heap.debugDescription)") } - + public func peek() -> T? { assert(self.heap.checkHeapProperty(), "broken heap: \(self.heap.debugDescription)") return self.heap.storage.first } - + public var isEmpty: Bool { assert(self.heap.checkHeapProperty(), "broken heap: \(self.heap.debugDescription)") return self.heap.storage.isEmpty } - + public mutating func pop() -> T? { assert(self.heap.checkHeapProperty(), "broken heap: \(self.heap.debugDescription)") return self.heap.removeRoot() diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index aa6c4dec3..57067ccc9 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -71,4 +71,4 @@ import XCTest testCase(TypeAssistedChannelHandlerTest.allTests), testCase(UtilitiesTest.allTests), ]) -#endif \ No newline at end of file +#endif diff --git a/Tests/NIOHTTP1Tests/HTTPRequestEncoderTest.swift b/Tests/NIOHTTP1Tests/HTTPRequestEncoderTest.swift index cb1bb05c3..d9764aa43 100644 --- a/Tests/NIOHTTP1Tests/HTTPRequestEncoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPRequestEncoderTest.swift @@ -28,7 +28,7 @@ class HTTPRequestEncoderTests: XCTestCase { defer { XCTAssertEqual(.some(false), try? channel.finish()) } - + try channel.pipeline.add(handler: HTTPRequestEncoder()).wait() var request = HTTPRequestHead(version: HTTPVersion(major: 1, minor:1), method: method, uri: "/uri") request.headers = headers @@ -39,7 +39,7 @@ class HTTPRequestEncoderTests: XCTestCase { fatalError("Could not read ByteBuffer from channel") } } - + func testNoAutoHeadersForHEAD() throws { let writtenData = try sendRequest(withMethod: .HEAD, andHeaders: HTTPHeaders()) writtenData.assertContainsOnly("HEAD /uri HTTP/1.1\r\n\r\n") @@ -59,32 +59,32 @@ class HTTPRequestEncoderTests: XCTestCase { writtenData = try sendRequest(withMethod: .GET, andHeaders: headers) writtenData.assertContainsOnly("GET /uri HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n") } - + func testNoContentLengthHeadersForHEAD() throws { let headers = HTTPHeaders([("content-length", "0")]) let writtenData = try sendRequest(withMethod: .HEAD, andHeaders: headers) writtenData.assertContainsOnly("HEAD /uri HTTP/1.1\r\n\r\n") } - + func testNoTransferEncodingHeadersForHEAD() throws { let headers = HTTPHeaders([("transfer-encoding", "chunked")]) let writtenData = try sendRequest(withMethod: .HEAD, andHeaders: headers) writtenData.assertContainsOnly("HEAD /uri HTTP/1.1\r\n\r\n") } - + func testNoChunkedEncodingForHTTP10() throws { let channel = EmbeddedChannel() defer { XCTAssertEqual(.some(false), try? channel.finish()) } - + XCTAssertNoThrow(try channel.pipeline.add(handler: HTTPRequestEncoder()).wait()) - + // This request contains neither Transfer-Encoding: chunked or Content-Length. let request = HTTPRequestHead(version: HTTPVersion(major: 1, minor:0), method: .GET, uri: "/uri") XCTAssertNoThrow(try channel.writeOutbound(HTTPClientRequestPart.head(request))) let writtenData: IOData = channel.readOutbound()! - + switch writtenData { case .byteBuffer(let b): let writtenResponse = b.getString(at: b.readerIndex, length: b.readableBytes)! @@ -93,20 +93,20 @@ class HTTPRequestEncoderTests: XCTestCase { XCTFail("Unexpected file region") } } - + func testBody() throws { let channel = EmbeddedChannel() defer { XCTAssertEqual(.some(false), try? channel.finish()) } - + try channel.pipeline.add(handler: HTTPRequestEncoder()).wait() var request = HTTPRequestHead(version: HTTPVersion(major: 1, minor:1), method: .POST, uri: "/uri") request.headers.add(name: "content-length", value: "4") - + var buf = channel.allocator.buffer(capacity: 4) buf.write(staticString: "test") - + XCTAssertNoThrow(try channel.writeOutbound(HTTPClientRequestPart.head(request))) XCTAssertNoThrow(try channel.writeOutbound(HTTPClientRequestPart.body(.byteBuffer(buf)))) XCTAssertNoThrow(try channel.writeOutbound(HTTPClientRequestPart.end(nil))) @@ -115,7 +115,7 @@ class HTTPRequestEncoderTests: XCTestCase { assertOutboundContainsOnly(channel, "test") assertOutboundContainsOnly(channel, "") } - + private func assertOutboundContainsOnly(_ channel: EmbeddedChannel, _ expected: String) { if case .some(.byteBuffer(let buffer)) = channel.readOutbound() { buffer.assertContainsOnly(expected) diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index 7aa08adf7..692626a7d 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -42,7 +42,7 @@ extension Array where Array.Element == ByteBuffer { } return out } - + public func allAsString() -> String? { return String(decoding: self.allAsBytes(), as: UTF8.self) } @@ -88,22 +88,22 @@ class HTTPServerClientTest : XCTestCase { case byteBuffer case fileRegion } - + private class SimpleHTTPServer: ChannelInboundHandler { typealias InboundIn = HTTPServerRequestPart typealias OutboundOut = HTTPServerResponsePart - + private let mode: SendMode private let fileManager = FileManager.default private var files: [String] = Array() private var seenEnd: Bool = false private var sentEnd: Bool = false private var isOpen: Bool = true - + init(_ mode: SendMode) { self.mode = mode } - + private func outboundBody(_ buffer: ByteBuffer) -> (body: HTTPServerResponsePart, destructor: () -> Void) { switch mode { case .byteBuffer: @@ -120,7 +120,7 @@ class HTTPServerClientTest : XCTestCase { } #endif files.append(filePath) - + let content = buffer.getData(at: 0, length: buffer.readableBytes)! XCTAssertNoThrow(try content.write(to: URL(fileURLWithPath: filePath))) let fh = try! FileHandle(path: filePath) @@ -130,7 +130,7 @@ class HTTPServerClientTest : XCTestCase { return (.body(.fileRegion(region)), { try! fh.close() }) } } - + public func handlerRemoved(ctx: ChannelHandlerContext) { for f in files { _ = try? fileManager.removeItem(atPath: f) @@ -150,7 +150,7 @@ class HTTPServerClientTest : XCTestCase { ctx.write(self.wrapOutboundOut(r), promise: nil) var b = ctx.channel.allocator.buffer(capacity: replyString.count) b.write(string: replyString) - + let outbound = self.outboundBody(b) ctx.write(self.wrapOutboundOut(outbound.body)).whenComplete { outbound.destructor() @@ -172,7 +172,7 @@ class HTTPServerClientTest : XCTestCase { for i in 1...10 { b.clear() b.write(string: "\(i)") - + let outbound = self.outboundBody(b) ctx.write(self.wrapOutboundOut(outbound.body)).mapIfError { error in XCTFail("unexpected error \(error)") @@ -198,7 +198,7 @@ class HTTPServerClientTest : XCTestCase { for i in 1...10 { b.clear() b.write(string: "\(i)") - + let outbound = self.outboundBody(b) ctx.write(self.wrapOutboundOut(outbound.body)).mapIfError { error in XCTFail("unexpected error \(error)") @@ -301,11 +301,11 @@ class HTTPServerClientTest : XCTestCase { func testSimpleGetByteBuffer() throws { try testSimpleGet(.byteBuffer) } - + func testSimpleGetFileRegion() throws { try testSimpleGet(.fileRegion) } - + private class HTTPClientResponsePartAssertHandler: ArrayAccumulationHandler { public init(_ expectedVersion: HTTPVersion, _ expectedStatus: HTTPResponseStatus, _ expectedHeaders: HTTPHeaders, _ expectedBody: String?, _ expectedTrailers: HTTPHeaders? = nil) { super.init { parts in @@ -320,7 +320,7 @@ class HTTPServerClientTest : XCTestCase { } else { XCTFail("unexpected type on index 0 \(parts[0])") } - + var i = 1 var bytes: [UInt8] = [] while i < parts.count - 1 { @@ -333,9 +333,9 @@ class HTTPServerClientTest : XCTestCase { } i += 1 } - + XCTAssertEqual(expectedBody, String(decoding: bytes, as: UTF8.self)) - + if case .end(let trailers) = parts[parts.count - 1] { XCTAssertEqual(expectedTrailers, trailers) } else { @@ -344,7 +344,7 @@ class HTTPServerClientTest : XCTestCase { } } } - + private func testSimpleGet(_ mode: SendMode) throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { @@ -354,14 +354,14 @@ class HTTPServerClientTest : XCTestCase { var expectedHeaders = HTTPHeaders() expectedHeaders.add(name: "content-length", value: "14") expectedHeaders.add(name: "connection", value: "close") - + let accumulation = HTTPClientResponsePartAssertHandler(HTTPVersion(major: 1, minor: 1), .ok, expectedHeaders, "Hello World!\r\n") - + let numBytes = 16 * 1024 let httpHandler = SimpleHTTPServer(mode) let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) - + // Set the handlers that are appled to the accepted Channels .childChannelInitializer { channel in // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline. @@ -369,11 +369,11 @@ class HTTPServerClientTest : XCTestCase { channel.pipeline.add(handler: httpHandler) } }.bind(host: "127.0.0.1", port: 0).wait() - + defer { XCTAssertNoThrow(try serverChannel.syncCloseAcceptingAlreadyClosed()) } - + let clientChannel = try ClientBootstrap(group: group) .channelInitializer { channel in channel.pipeline.addHTTPClientHandlers().then { @@ -382,11 +382,11 @@ class HTTPServerClientTest : XCTestCase { } .connect(to: serverChannel.localAddress!) .wait() - + defer { XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed()) } - + var head = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/helloworld") head.headers.add(name: "Host", value: "apple.com") clientChannel.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil) @@ -394,32 +394,32 @@ class HTTPServerClientTest : XCTestCase { accumulation.syncWaitForCompletion() } - + func testSimpleGetChunkedEncodingByteBuffer() throws { try testSimpleGetChunkedEncoding(.byteBuffer) } - + func testSimpleGetChunkedEncodingFileRegion() throws { try testSimpleGetChunkedEncoding(.fileRegion) } - + private func testSimpleGetChunkedEncoding(_ mode: SendMode) throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + var expectedHeaders = HTTPHeaders() expectedHeaders.add(name: "transfer-encoding", value: "chunked") expectedHeaders.add(name: "connection", value: "close") - + let accumulation = HTTPClientResponsePartAssertHandler(HTTPVersion(major: 1, minor: 1), .ok, expectedHeaders, "12345678910") - + let numBytes = 16 * 1024 let httpHandler = SimpleHTTPServer(mode) let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) - + // Set the handlers that are appled to the accepted Channels .childChannelInitializer { channel in // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline. @@ -427,11 +427,11 @@ class HTTPServerClientTest : XCTestCase { channel.pipeline.add(handler: httpHandler) } }.bind(host: "127.0.0.1", port: 0).wait() - + defer { XCTAssertNoThrow(try serverChannel.syncCloseAcceptingAlreadyClosed()) } - + let clientChannel = try ClientBootstrap(group: group) .channelInitializer { channel in channel.pipeline.addHTTPClientHandlers().then { @@ -440,11 +440,11 @@ class HTTPServerClientTest : XCTestCase { } .connect(to: serverChannel.localAddress!) .wait() - + defer { XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed()) } - + var head = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/count-to-ten") head.headers.add(name: "Host", value: "apple.com") clientChannel.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil) @@ -455,11 +455,11 @@ class HTTPServerClientTest : XCTestCase { func testSimpleGetTrailersByteBuffer() throws { try testSimpleGetTrailers(.byteBuffer) } - + func testSimpleGetTrailersFileRegion() throws { try testSimpleGetTrailers(.fileRegion) } - + private func testSimpleGetTrailers(_ mode: SendMode) throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { @@ -469,13 +469,13 @@ class HTTPServerClientTest : XCTestCase { var expectedHeaders = HTTPHeaders() expectedHeaders.add(name: "transfer-encoding", value: "chunked") expectedHeaders.add(name: "connection", value: "close") - + var expectedTrailers = HTTPHeaders() expectedTrailers.add(name: "x-url-path", value: "/trailers") expectedTrailers.add(name: "x-should-trail", value: "sure") - + let accumulation = HTTPClientResponsePartAssertHandler(HTTPVersion(major: 1, minor: 1), .ok, expectedHeaders, "12345678910", expectedTrailers) - + let numBytes = 16 * 1024 let httpHandler = SimpleHTTPServer(mode) let serverChannel = try ServerBootstrap(group: group) @@ -507,14 +507,14 @@ class HTTPServerClientTest : XCTestCase { head.headers.add(name: "Host", value: "apple.com") clientChannel.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil) try clientChannel.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil))).wait() - + accumulation.syncWaitForCompletion() } func testMassiveResponseByteBuffer() throws { try testMassiveResponse(.byteBuffer) } - + func testMassiveResponseFileRegion() throws { try testMassiveResponse(.fileRegion) } diff --git a/Tests/NIOPriorityQueueTests/HeapTests.swift b/Tests/NIOPriorityQueueTests/HeapTests.swift index 09596e266..2083c4fd7 100644 --- a/Tests/NIOPriorityQueueTests/HeapTests.swift +++ b/Tests/NIOPriorityQueueTests/HeapTests.swift @@ -62,7 +62,7 @@ class HeapTests: XCTestCase { XCTAssertEqual(-1, minHeapInputPtr) XCTAssertEqual(input.count, maxHeapInputPtr) } - + func testSortedAsc() throws { var maxHeap = Heap(type: .maxHeap) var minHeap = Heap(type: .minHeap) diff --git a/Tests/NIOTests/BaseObjectsTest.swift b/Tests/NIOTests/BaseObjectsTest.swift index d1d24352e..b1833ac3a 100644 --- a/Tests/NIOTests/BaseObjectsTest.swift +++ b/Tests/NIOTests/BaseObjectsTest.swift @@ -32,7 +32,7 @@ class BaseObjectTest: XCTestCase { XCTFail("tryAs didn't work") } } - + func testNIOIODataConversion() { let expected = IOData.byteBuffer(ByteBufferAllocator().buffer(capacity: 1024)) let asAny = NIOAny(expected) @@ -49,7 +49,7 @@ class BaseObjectTest: XCTestCase { XCTFail("tryAs didn't work") } } - + func testNIOFileRegionConversion() { let handle = FileHandle(descriptor: -1) let expected = FileRegion(fileHandle: handle, readerIndex: 1, endIndex: 2) @@ -71,7 +71,7 @@ class BaseObjectTest: XCTestCase { XCTFail("tryAs didn't work") } } - + func testBadConversions() { let handle = FileHandle(descriptor: -1) let bb = ByteBufferAllocator().buffer(capacity: 1024) @@ -81,18 +81,18 @@ class BaseObjectTest: XCTestCase { XCTAssertNoThrow(try handle.takeDescriptorOwnership()) } let id = IOData.byteBuffer(bb) - + XCTAssertNil(NIOAny(bb).tryAsFileRegion()) XCTAssertNil(NIOAny(fr).tryAsByteBuffer()) XCTAssertNil(NIOAny(id).tryAsFileRegion()) } - + func testByteBufferFromIOData() { let expected = ByteBufferAllocator().buffer(capacity: 1024) let wrapped = IOData.byteBuffer(expected) XCTAssertEqual(expected, NIOAny(wrapped).tryAsByteBuffer()) } - + func testFileRegionFromIOData() { let handle = FileHandle(descriptor: -1) let expected = FileRegion(fileHandle: handle, readerIndex: 1, endIndex: 2) @@ -103,7 +103,7 @@ class BaseObjectTest: XCTestCase { let wrapped = IOData.fileRegion(expected) XCTAssert(expected == NIOAny(wrapped).tryAsFileRegion()) } - + func testIODataEquals() { let handle = FileHandle(descriptor: -1) var bb1 = ByteBufferAllocator().buffer(capacity: 1024) diff --git a/Tests/NIOTests/BlockingIOThreadPoolTest.swift b/Tests/NIOTests/BlockingIOThreadPoolTest.swift index e6b54060b..a5fb0b857 100644 --- a/Tests/NIOTests/BlockingIOThreadPoolTest.swift +++ b/Tests/NIOTests/BlockingIOThreadPoolTest.swift @@ -23,7 +23,7 @@ class BlockingIOThreadPoolTest: XCTestCase { try threadPool.syncShutdownGracefully() try threadPool.syncShutdownGracefully() } - + func testStateCancelled() throws { let threadPool = BlockingIOThreadPool(numberOfThreads: 17) let group = DispatchGroup() @@ -35,7 +35,7 @@ class BlockingIOThreadPoolTest: XCTestCase { group.wait() try threadPool.syncShutdownGracefully() } - + func testStateActive() throws { let threadPool = BlockingIOThreadPool(numberOfThreads: 17) threadPool.start() diff --git a/Tests/NIOTests/ByteBufferTest.swift b/Tests/NIOTests/ByteBufferTest.swift index 724d9e377..7b4d22a19 100644 --- a/Tests/NIOTests/ByteBufferTest.swift +++ b/Tests/NIOTests/ByteBufferTest.swift @@ -37,7 +37,7 @@ class ByteBufferTest: XCTestCase { XCTAssertEqual(v, buffer.readInteger()) XCTAssertEqual(0, buffer.readableBytes) } - + override func setUp() { super.setUp() @@ -68,12 +68,12 @@ class ByteBufferTest: XCTestCase { otherBuffer.write(string: "oh hi") XCTAssertEqual(otherBuffer, buf) } - + func testSimpleReadTest() throws { buf.withUnsafeReadableBytes { ptr in XCTAssertEqual(ptr.count, 0) } - + buf.write(string: "Hello world!") buf.withUnsafeReadableBytes { ptr in XCTAssertEqual(12, ptr.count) @@ -133,13 +133,13 @@ class ByteBufferTest: XCTestCase { XCTAssertEqual(expected, String(decoding: d!, as: UTF8.self)) } } - + func testString() { let written = buf.write(string: "Hello")! let string = buf.getString(at: 0, length: written) XCTAssertEqual("Hello", string) } - + func testSliceEasy() { buf.write(string: "0123456789abcdefg") for i in 0..<16 { @@ -158,7 +158,7 @@ class ByteBufferTest: XCTestCase { XCTAssertEqual("hello", s) } } - + func testSetExpandsBufferOnUpperBoundsCheckFailure() { let initialCapacity = buf.capacity XCTAssertEqual(5, buf.set(string: "oh hi", at: buf.capacity)) @@ -173,13 +173,13 @@ class ByteBufferTest: XCTestCase { XCTAssertEqual(buf, b) XCTAssertNotEqual(buf, a) } - + func testWithMutableReadPointerMovesReaderIndexAndReturnsNumBytesConsumed() { XCTAssertEqual(0, buf.readerIndex) // We use mutable read pointers when we're consuming the data // so first we need some data there! buf.write(string: "hello again") - + let bytesConsumed = buf.readWithUnsafeReadableBytes { dst in // Pretend we did some operation which made use of entire 11 byte string return 11 @@ -190,57 +190,57 @@ class ByteBufferTest: XCTestCase { func testWithMutableWritePointerMovesWriterIndexAndReturnsNumBytesWritten() { XCTAssertEqual(0, buf.writerIndex) - + let bytesWritten = buf.writeWithUnsafeMutableBytes { (_: UnsafeMutableRawBufferPointer) in return 5 } XCTAssertEqual(5, bytesWritten) XCTAssertEqual(5, buf.writerIndex) } - + func testChangeCapacityWhenEnoughAvailable() throws { let oldCapacity = buf.capacity buf.changeCapacity(to: buf.capacity - 1) XCTAssertLessThanOrEqual(buf.capacity, oldCapacity) } - + func testChangeCapacityWhenNotEnoughMaxCapacity() throws { buf = allocator.buffer(capacity: 16) let oldCapacity = buf.capacity buf.changeCapacity(to: buf.capacity + 1) XCTAssertGreaterThan(buf.capacity, oldCapacity) } - + func testSetGetInt8() throws { try setGetInt(index: 0, v: Int8.max) } - + func testSetGetInt16() throws { try setGetInt(index: 1, v: Int16.max) } - + func testSetGetInt32() throws { try setGetInt(index: 2, v: Int32.max) } - + func testSetGetInt64() throws { try setGetInt(index: 3, v: Int64.max) } - + func testSetGetUInt8() throws { try setGetInt(index: 4, v: UInt8.max) } - + func testSetGetUInt16() throws { try setGetInt(index: 5, v: UInt16.max) } - + func testSetGetUInt32() throws { try setGetInt(index: 6, v: UInt32.max) } - + func testSetGetUInt64() throws { try setGetInt(index: 7, v: UInt64.max) } - + func testWriteReadInt8() throws { try writeReadInt(v: Int8.max) } @@ -248,31 +248,31 @@ class ByteBufferTest: XCTestCase { func testWriteReadInt16() throws { try writeReadInt(v: Int16.max) } - + func testWriteReadInt32() throws { try writeReadInt(v: Int32.max) } - + func testWriteReadInt64() throws { try writeReadInt(v: Int32.max) } - + func testWriteReadUInt8() throws { try writeReadInt(v: UInt8.max) } - + func testWriteReadUInt16() throws { try writeReadInt(v: UInt16.max) } - + func testWriteReadUInt32() throws { try writeReadInt(v: UInt32.max) } - + func testWriteReadUInt64() throws { try writeReadInt(v: UInt32.max) } - + func testSlice() throws { var buffer = allocator.buffer(capacity: 32) XCTAssertEqual(MemoryLayout.size, buffer.write(integer: UInt64.max)) @@ -282,7 +282,7 @@ class ByteBufferTest: XCTestCase { XCTAssertEqual(MemoryLayout.size, buffer.readableBytes) XCTAssertEqual(UInt64.max, buffer.readInteger()) } - + func testSliceWithParams() throws { var buffer = allocator.buffer(capacity: 32) XCTAssertEqual(MemoryLayout.size, buffer.write(integer: UInt64.max)) @@ -292,7 +292,7 @@ class ByteBufferTest: XCTestCase { XCTAssertEqual(MemoryLayout.size, buffer.readableBytes) XCTAssertEqual(UInt64.max, buffer.readInteger()) } - + func testReadSlice() throws { var buffer = allocator.buffer(capacity: 32) XCTAssertEqual(MemoryLayout.size, buffer.write(integer: UInt64.max)) @@ -303,7 +303,7 @@ class ByteBufferTest: XCTestCase { let value: UInt64? = buffer.readInteger() XCTAssertTrue(value == nil) } - + func testSliceNoCopy() throws { var buffer = allocator.buffer(capacity: 32) XCTAssertEqual(MemoryLayout.size, buffer.write(integer: UInt64.max)) @@ -315,25 +315,25 @@ class ByteBufferTest: XCTestCase { } } } - + func testSetGetData() throws { var buffer = allocator.buffer(capacity: 32) let data = Data(bytes: [1, 2, 3]) - + XCTAssertEqual(3, buffer.set(bytes: data, at: 0)) XCTAssertEqual(0, buffer.readableBytes) XCTAssertEqual(data, buffer.getData(at: 0, length: 3)) } - + func testWriteReadData() throws { var buffer = allocator.buffer(capacity: 32) let data = Data(bytes: [1, 2, 3]) - + XCTAssertEqual(3, buffer.write(bytes: data)) XCTAssertEqual(3, buffer.readableBytes) XCTAssertEqual(data, buffer.readData(length: 3)) } - + func testDiscardReadBytes() throws { var buffer = allocator.buffer(capacity: 32) buffer.write(integer: UInt8(1)) @@ -355,7 +355,7 @@ class ByteBufferTest: XCTestCase { XCTAssertTrue(buffer.discardReadBytes()) XCTAssertFalse(buffer.discardReadBytes()) } - + func testDiscardReadBytesCoW() throws { var buffer = allocator.buffer(capacity: 32) let bytesWritten = buffer.write(bytes: "0123456789abcdef0123456789ABCDEF".data(using: .utf8)!) @@ -396,7 +396,7 @@ class ByteBufferTest: XCTestCase { testAssumptionOriginalBuffer(&buffer) } - + func testDiscardReadBytesSlice() throws { var buffer = allocator.buffer(capacity: 32) buffer.write(integer: UInt8(1)) @@ -500,7 +500,7 @@ class ByteBufferTest: XCTestCase { XCTAssertEqual("0123456789abcdefX".data(using: .utf8)!, Data(buffer: bPtr)) } } - + func testExpansion2() throws { var buf = allocator.buffer(capacity: 2) XCTAssertEqual(2, buf.capacity) @@ -710,26 +710,26 @@ class ByteBufferTest: XCTestCase { var actualGood = buf.readSlice(length: 4) XCTAssertEqual(Data([0, 1, 2, 3]), actualGood?.readData(length: 4)) } - + func testSetBuffer() throws { var src = allocator.buffer(capacity: 4) src.write(bytes: Data([0, 1, 2, 3])) - + buf.set(buffer: src, at: 1) - + /* Should bit increase the writerIndex of the src buffer */ XCTAssertEqual(4, src.readableBytes) XCTAssertEqual(0, buf.readableBytes) - + XCTAssertEqual(Data([0, 1, 2, 3]), buf.getData(at: 1, length: 4)) } - + func testWriteBuffer() throws { var src = allocator.buffer(capacity: 4) src.write(bytes: Data([0, 1, 2, 3])) - + buf.write(buffer: &src) - + /* Should increase the writerIndex of the src buffer */ XCTAssertEqual(0, src.readableBytes) XCTAssertEqual(4, buf.readableBytes) diff --git a/Tests/NIOTests/ChannelPipelineTest.swift b/Tests/NIOTests/ChannelPipelineTest.swift index 887eda19e..7385a5ba2 100644 --- a/Tests/NIOTests/ChannelPipelineTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest.swift @@ -17,14 +17,14 @@ import NIOConcurrencyHelpers @testable import NIO class ChannelPipelineTest: XCTestCase { - + func testAddAfterClose() throws { - + let channel = EmbeddedChannel() _ = channel.close() - + channel.pipeline.removeHandlers() - + let handler = DummyHandler() defer { XCTAssertFalse(handler.handlerAddedCalled.load()) @@ -37,7 +37,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertEqual(err, .ioOnClosedChannel) } } - + private final class DummyHandler: ChannelHandler { let handlerAddedCalled = Atomic(value: false) let handlerRemovedCalled = Atomic(value: false) @@ -45,29 +45,29 @@ class ChannelPipelineTest: XCTestCase { public func handlerAdded(ctx: ChannelHandlerContext) { handlerAddedCalled.store(true) } - + public func handlerRemoved(ctx: ChannelHandlerContext) { handlerRemovedCalled.store(true) } } - + func testOutboundOrdering() throws { - + let channel = EmbeddedChannel() var buf = channel.allocator.buffer(capacity: 1024) buf.write(string: "hello") - + _ = try channel.pipeline.add(handler: TestChannelOutboundHandler { data in XCTAssertEqual(1, data) return buf }).wait() - + _ = try channel.pipeline.add(handler: TestChannelOutboundHandler { data in XCTAssertEqual("msg", data) return 1 }).wait() - + try channel.writeAndFlush(NIOAny("msg")).wait() if let data = channel.readOutbound() { XCTAssertEqual(IOData.byteBuffer(buf), data) @@ -78,34 +78,34 @@ class ChannelPipelineTest: XCTestCase { XCTAssertFalse(try channel.finish()) } - + func testConnectingDoesntCallBind() throws { let channel = EmbeddedChannel() var ipv4SocketAddress = sockaddr_in() ipv4SocketAddress.sin_port = (12345 as UInt16).bigEndian let sa = SocketAddress(ipv4SocketAddress, host: "foobar.com") - + _ = try channel.pipeline.add(handler: NoBindAllowed()).wait() _ = try channel.pipeline.add(handler: TestChannelOutboundHandler { data in return data }).wait() - + _ = try channel.connect(to: sa).wait() defer { XCTAssertFalse(try channel.finish()) } } - + private final class TestChannelOutboundHandler: ChannelOutboundHandler { typealias OutboundIn = In typealias OutboundOut = Out - + private let body: (OutboundIn) throws -> OutboundOut - + init(_ body: @escaping (OutboundIn) throws -> OutboundOut) { self.body = body } - + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { do { ctx.write(self.wrapOutboundOut(try body(self.unwrapOutboundIn(data))), promise: promise) @@ -114,15 +114,15 @@ class ChannelPipelineTest: XCTestCase { } } } - + private final class NoBindAllowed: ChannelOutboundHandler { typealias OutboundIn = ByteBuffer typealias OutboundOut = ByteBuffer - + enum TestFailureError: Error { case CalledBind } - + public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { promise!.fail(error: TestFailureError.CalledBind) } diff --git a/Tests/NIOTests/ChannelTests.swift b/Tests/NIOTests/ChannelTests.swift index 9d40ce823..e433afbe8 100644 --- a/Tests/NIOTests/ChannelTests.swift +++ b/Tests/NIOTests/ChannelTests.swift @@ -38,7 +38,7 @@ class ChannelLifecycleHandler: ChannelInboundHandler { currentState = state stateHistory.append(state) } - + public func channelRegistered(ctx: ChannelHandlerContext) { XCTAssertEqual(currentState, .unregistered) XCTAssertFalse(ctx.channel.isActive) @@ -1043,7 +1043,7 @@ public class ChannelTests: XCTestCase { defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + do { // This must throw as 198.51.100.254 is reserved for documentation only _ = try ClientBootstrap(group: group) @@ -1079,20 +1079,20 @@ public class ChannelTests: XCTestCase { } } } - + func testCloseOutput() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + let server = try ServerSocket(protocolFamily: PF_INET) defer { XCTAssertNoThrow(try server.close()) } try server.bind(to: SocketAddress.newAddressResolving(host: "127.0.0.1", port: 0)) try server.listen() - + let byteCountingHandler = ByteCountingHandler(numBytes: 4, promise: group.next().newPromise()) let verificationHandler = ShutdownVerificationHandler(shutdownEvent: .output, promise: group.next().newPromise()) let future = ClientBootstrap(group: group) @@ -1111,13 +1111,13 @@ public class ChannelTests: XCTestCase { defer { XCTAssertNoThrow(try channel.close(mode: .all).wait()) } - + var buffer = channel.allocator.buffer(capacity: 12) buffer.write(string: "1234") try channel.writeAndFlush(NIOAny(buffer)).wait() try channel.close(mode: .output).wait() - + verificationHandler.waitForEvent() do { try channel.writeAndFlush(NIOAny(buffer)).wait() @@ -1136,28 +1136,28 @@ public class ChannelTests: XCTestCase { } try byteCountingHandler.assertReceived(buffer: buffer) } - + func testCloseInput() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + let server = try ServerSocket(protocolFamily: PF_INET) defer { XCTAssertNoThrow(try server.close()) } try server.bind(to: SocketAddress.newAddressResolving(host: "127.0.0.1", port: 0)) try server.listen() - + class VerifyNoReadHandler : ChannelInboundHandler { typealias InboundIn = ByteBuffer - + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { XCTFail("Received data: \(data)") } } - + let verificationHandler = ShutdownVerificationHandler(shutdownEvent: .input, promise: group.next().newPromise()) let future = ClientBootstrap(group: group) .channelInitializer { channel in @@ -1170,48 +1170,48 @@ public class ChannelTests: XCTestCase { defer { XCTAssertNoThrow(try accepted.close()) } - + let channel = try future.wait() defer { XCTAssertNoThrow(try channel.close(mode: .all).wait()) } - + try channel.close(mode: .input).wait() - + verificationHandler.waitForEvent() - + var buffer = channel.allocator.buffer(capacity: 12) buffer.write(string: "1234") - + let written = try buffer.withUnsafeReadableBytes { p in try accepted.write(pointer: p.baseAddress!.assumingMemoryBound(to: UInt8.self), size: 4) } - + switch written { case .processed(let numBytes): XCTAssertEqual(4, numBytes) default: XCTFail() } - + try channel.eventLoop.submit { // Dummy task execution to give some time for an actual read to open (which should not happen as we closed the input). }.wait() } - + func testHalfClosure() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + let server = try ServerSocket(protocolFamily: PF_INET) defer { XCTAssertNoThrow(try server.close()) } try server.bind(to: SocketAddress.newAddressResolving(host: "127.0.0.1", port: 0)) try server.listen() - + let verificationHandler = ShutdownVerificationHandler(shutdownEvent: .input, promise: group.next().newPromise()) let future = ClientBootstrap(group: group) @@ -1224,40 +1224,40 @@ public class ChannelTests: XCTestCase { defer { XCTAssertNoThrow(try accepted.close()) } - + let channel = try future.wait() defer { XCTAssertNoThrow(try channel.close(mode: .all).wait()) } - + try accepted.shutdown(how: .WR) - + verificationHandler.waitForEvent() - + var buffer = channel.allocator.buffer(capacity: 12) buffer.write(string: "1234") - + try channel.writeAndFlush(NIOAny(buffer)).wait() } - + enum ShutDownEvent { case input case output } private class ShutdownVerificationHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer - + private var inputShutdownEventReceived = false private var outputShutdownEventReceived = false - + private let promise: EventLoopPromise private let shutdownEvent: ShutDownEvent - + init(shutdownEvent: ShutDownEvent, promise: EventLoopPromise) { self.promise = promise self.shutdownEvent = shutdownEvent } - + public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { switch event { case let ev as ChannelEvent: @@ -1265,30 +1265,30 @@ public class ChannelTests: XCTestCase { case .inputClosed: XCTAssertFalse(inputShutdownEventReceived) inputShutdownEventReceived = true - + if shutdownEvent == .input { promise.succeed(result: ()) } case .outputClosed: XCTAssertFalse(outputShutdownEventReceived) outputShutdownEventReceived = true - + if shutdownEvent == .output { promise.succeed(result: ()) } } - + fallthrough default: ctx.fireUserInboundEventTriggered(event) } } - + public func waitForEvent() { // We always notify it with a success so just force it with ! try! promise.futureResult.wait() } - + public func channelInactive(ctx: ChannelHandlerContext) { switch shutdownEvent { case .input: @@ -1298,7 +1298,7 @@ public class ChannelTests: XCTestCase { XCTAssertFalse(inputShutdownEventReceived) XCTAssertTrue(outputShutdownEventReceived) } - + promise.succeed(result: ()) } } diff --git a/Tests/NIOTests/CircularBufferTests.swift b/Tests/NIOTests/CircularBufferTests.swift index 63fe8fba0..29e888a79 100644 --- a/Tests/NIOTests/CircularBufferTests.swift +++ b/Tests/NIOTests/CircularBufferTests.swift @@ -21,7 +21,7 @@ class CircularBufferTests: XCTestCase { ring.append(1) XCTAssertEqual(1, ring.removeFirst()) } - + func testAddRemoveInALoop() { var ring = CircularBuffer(initialRingCapacity: 8) for f in 0..<1000 { @@ -29,7 +29,7 @@ class CircularBufferTests: XCTestCase { XCTAssertEqual(f, ring.removeFirst()) } } - + func testAddAllRemoveAll() { var ring = CircularBuffer(initialRingCapacity: 8) for f in 0..<1000 { @@ -39,7 +39,7 @@ class CircularBufferTests: XCTestCase { XCTAssertEqual(f, ring.removeFirst()) } } - + func testHarderExpansion() { var ring = CircularBuffer(initialRingCapacity: 3) XCTAssertEqual(ring.indices, 0..<0) @@ -48,45 +48,45 @@ class CircularBufferTests: XCTestCase { XCTAssertEqual(ring.count, 1) XCTAssertEqual(ring[0], 1) XCTAssertEqual(ring.indices, 0..<1) - + ring.append(2) XCTAssertEqual(ring.count, 2) XCTAssertEqual(ring[0], 1) XCTAssertEqual(ring[1], 2) XCTAssertEqual(ring.indices, 0..<2) - + ring.append(3) XCTAssertEqual(ring.count, 3) XCTAssertEqual(ring[0], 1) XCTAssertEqual(ring[1], 2) XCTAssertEqual(ring[2], 3) XCTAssertEqual(ring.indices, 0..<3) - - + + XCTAssertEqual(1, ring.removeFirst()) XCTAssertEqual(ring.count, 2) XCTAssertEqual(ring[0], 2) XCTAssertEqual(ring[1], 3) XCTAssertEqual(ring.indices, 0..<2) - + XCTAssertEqual(2, ring.removeFirst()) XCTAssertEqual(ring.count, 1) XCTAssertEqual(ring[0], 3) XCTAssertEqual(ring.indices, 0..<1) - + ring.append(5) XCTAssertEqual(ring.count, 2) XCTAssertEqual(ring[0], 3) XCTAssertEqual(ring[1], 5) XCTAssertEqual(ring.indices, 0..<2) - + ring.append(6) XCTAssertEqual(ring.count, 3) XCTAssertEqual(ring[0], 3) XCTAssertEqual(ring[1], 5) XCTAssertEqual(ring[2], 6) XCTAssertEqual(ring.indices, 0..<3) - + ring.append(7) XCTAssertEqual(ring.count, 4) XCTAssertEqual(ring[0], 3) diff --git a/Tests/NIOTests/CodecTest.swift b/Tests/NIOTests/CodecTest.swift index f793fabf4..69eb6dc24 100644 --- a/Tests/NIOTests/CodecTest.swift +++ b/Tests/NIOTests/CodecTest.swift @@ -56,8 +56,8 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundOut = Int32 var cumulationBuffer: ByteBuffer? - - + + func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { guard buffer.readableBytes >= MemoryLayout.size else { return .needMoreData @@ -111,29 +111,29 @@ public class ByteToMessageDecoderTest: XCTestCase { return .continue } } - + func testDecoder() throws { let channel = EmbeddedChannel() - + _ = try channel.pipeline.add(handler: ByteToInt32Decoder()).wait() - + var buffer = channel.allocator.buffer(capacity: 32) buffer.write(integer: Int32(1)) let writerIndex = buffer.writerIndex buffer.moveWriterIndex(to: writerIndex - 1) - + channel.pipeline.fireChannelRead(NIOAny(buffer)) XCTAssertNil(channel.readInbound()) - + channel.pipeline.fireChannelRead(NIOAny(buffer.getSlice(at: writerIndex - 1, length: 1)!)) - + var buffer2 = channel.allocator.buffer(capacity: 32) buffer2.write(integer: Int32(2)) buffer2.write(integer: Int32(3)) channel.pipeline.fireChannelRead(NIOAny(buffer2)) - + XCTAssertNoThrow(try channel.finish()) - + XCTAssertEqual(Int32(1), channel.readInbound()) XCTAssertEqual(Int32(2), channel.readInbound()) XCTAssertEqual(Int32(3), channel.readInbound()) @@ -240,7 +240,7 @@ public class ByteToMessageDecoderTest: XCTestCase { } public class MessageToByteEncoderTest: XCTestCase { - + private final class Int32ToByteEncoder : MessageToByteEncoder { typealias OutboundIn = Int32 typealias OutboundOut = ByteBuffer @@ -249,22 +249,22 @@ public class MessageToByteEncoderTest: XCTestCase { XCTAssertEqual(MemoryLayout.size, out.writableBytes) out.write(integer: value) } - + public func allocateOutBuffer(ctx: ChannelHandlerContext, data: Int32) throws -> ByteBuffer { return ctx.channel.allocator.buffer(capacity: MemoryLayout.size) } } - + private final class Int32ToByteEncoderWithDefaultImpl : MessageToByteEncoder { typealias OutboundIn = Int32 typealias OutboundOut = ByteBuffer - + public func encode(ctx: ChannelHandlerContext, data value: Int32, out: inout ByteBuffer) throws { XCTAssertEqual(MemoryLayout.size, 256) out.write(integer: value) } } - + func testEncoderOverrideAllocateOutBuffer() throws { try testEncoder(Int32ToByteEncoder()) } @@ -272,21 +272,21 @@ public class MessageToByteEncoderTest: XCTestCase { func testEncoder() throws { try testEncoder(Int32ToByteEncoderWithDefaultImpl()) } - + private func testEncoder(_ handler: ChannelHandler) throws { let channel = EmbeddedChannel() - + _ = try channel.pipeline.add(handler: Int32ToByteEncoder()).wait() - + _ = try channel.writeAndFlush(NIOAny(Int32(5))).wait() - + if case .some(.byteBuffer(var buffer)) = channel.readOutbound() { XCTAssertEqual(Int32(5), buffer.readInteger()) XCTAssertEqual(0, buffer.readableBytes) } else { XCTFail("couldn't read ByteBuffer from channel") } - + XCTAssertFalse(try channel.finish()) } diff --git a/Tests/NIOTests/EchoServerClientTest.swift b/Tests/NIOTests/EchoServerClientTest.swift index 49e6b5fd0..ddd9519ae 100644 --- a/Tests/NIOTests/EchoServerClientTest.swift +++ b/Tests/NIOTests/EchoServerClientTest.swift @@ -33,7 +33,7 @@ class EchoServerClientTest : XCTestCase { let udsTempDir = String(decoding: templateBytes, as: UTF8.self) return udsTempDir } - + func testEcho() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { @@ -44,7 +44,7 @@ class EchoServerClientTest : XCTestCase { let countingHandler = ByteCountingHandler(numBytes: numBytes, promise: group.next().newPromise()) let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) - + .childChannelInitializer { channel in channel.pipeline.add(handler: countingHandler) }.bind(host: "127.0.0.1", port: 0).wait() @@ -69,7 +69,7 @@ class EchoServerClientTest : XCTestCase { try countingHandler.assertReceived(buffer: buffer) } - + func testLotsOfUnflushedWrites() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { @@ -198,19 +198,19 @@ class EchoServerClientTest : XCTestCase { let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) .bind(host: "127.0.0.1", port: 0).wait() - + defer { _ = serverChannel.close() } - + let clientChannel = try ClientBootstrap(group: group) .channelInitializer { $0.pipeline.add(handler: handler) } .connect(to: serverChannel.localAddress!).wait() - + defer { _ = clientChannel.close() } - + handler.assertChannelActiveFired() } @@ -251,18 +251,18 @@ class EchoServerClientTest : XCTestCase { private final class ChannelActiveHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer - + private var promise: EventLoopPromise! = nil - + func handlerAdded(ctx: ChannelHandlerContext) { promise = ctx.channel.eventLoop.newPromise() } - + func channelActive(ctx: ChannelHandlerContext) { promise.succeed(result: ()) ctx.fireChannelActive() } - + func assertChannelActiveFired() { XCTAssert(promise.futureResult.fulfilled) } @@ -271,11 +271,11 @@ class EchoServerClientTest : XCTestCase { private final class EchoServer: ChannelInboundHandler { typealias InboundIn = ByteBuffer typealias OutboundOut = ByteBuffer - + func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { ctx.write(data, promise: nil) } - + func channelReadComplete(ctx: ChannelHandlerContext) { ctx.flush() } @@ -585,28 +585,28 @@ class EchoServerClientTest : XCTestCase { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + func testPendingReadProcessedAfterWriteError() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) let dpGroup = DispatchGroup() - + dpGroup.enter() - + let str = "hi there" let countingHandler = ByteCountingHandler(numBytes: str.utf8.count * 4, promise: group.next().newPromise()) class WriteHandler : ChannelInboundHandler { typealias InboundIn = ByteBuffer - + private var writeFailed = false - + func channelActive(ctx: ChannelHandlerContext) { var buffer = ctx.channel.allocator.buffer(capacity: 4) buffer.write(string: "test") writeUntilFailed(ctx, buffer) } - + private func writeUntilFailed(_ ctx: ChannelHandlerContext, _ buffer: ByteBuffer) { ctx.writeAndFlush(NIOAny(buffer)).whenComplete { ctx.eventLoop.execute { @@ -615,22 +615,22 @@ class EchoServerClientTest : XCTestCase { } } } - + class WriteWhenActiveHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer let str: String let dpGroup: DispatchGroup - + init(_ str: String, _ dpGroup: DispatchGroup) { self.str = str self.dpGroup = dpGroup } - + func channelActive(ctx: ChannelHandlerContext) { ctx.fireChannelActive() var buffer = ctx.channel.allocator.buffer(capacity: str.utf8.count) buffer.write(string: str) - + // write it four times and then close the connect. ctx.writeAndFlush(NIOAny(buffer)).then { ctx.writeAndFlush(NIOAny(buffer)) @@ -651,11 +651,11 @@ class EchoServerClientTest : XCTestCase { .childChannelInitializer { channel in channel.pipeline.add(handler: WriteWhenActiveHandler(str, dpGroup)) }.bind(host: "127.0.0.1", port: 0).wait() - + defer { _ = serverChannel.close() } - + let clientChannel = try ClientBootstrap(group: group) // We will only start reading once we wrote all data on the accepted channel. //.channelOption(ChannelOptions.autoRead, value: false) @@ -669,7 +669,7 @@ class EchoServerClientTest : XCTestCase { _ = clientChannel.close() } dpGroup.wait() - + var completeBuffer = clientChannel.allocator.buffer(capacity: str.utf8.count * 4) completeBuffer.write(string: str) completeBuffer.write(string: str) @@ -680,50 +680,50 @@ class EchoServerClientTest : XCTestCase { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + func testChannelErrorEOFNotFiredThroughPipeline() throws { - + class ErrorHandler : ChannelInboundHandler { typealias InboundIn = ByteBuffer private let promise: EventLoopPromise - + init(_ promise: EventLoopPromise) { self.promise = promise } - + public func errorCaught(ctx: ChannelHandlerContext, error: Error) { if let err = error as? ChannelError { XCTAssertNotEqual(ChannelError.eof, err) } } - + public func channelInactive(ctx: ChannelHandlerContext) { self.promise.succeed(result: ()) } } - + let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + let promise: EventLoopPromise = group.next().newPromise() - + let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) .childChannelInitializer { channel in channel.pipeline.add(handler: ErrorHandler(promise)) }.bind(host: "127.0.0.1", port: 0).wait() - + defer { XCTAssertNoThrow(try serverChannel.close().wait()) } - + let clientChannel = try ClientBootstrap(group: group) .connect(to: serverChannel.localAddress!).wait() XCTAssertNoThrow(try clientChannel.close().wait()) - + XCTAssertNoThrow(try promise.futureResult.wait()) } } diff --git a/Tests/NIOTests/EmbeddedChannelTest.swift b/Tests/NIOTests/EmbeddedChannelTest.swift index 50fe56480..166ca1b13 100644 --- a/Tests/NIOTests/EmbeddedChannelTest.swift +++ b/Tests/NIOTests/EmbeddedChannelTest.swift @@ -20,26 +20,26 @@ class EmbeddedChannelTest: XCTestCase { let channel = EmbeddedChannel() var buf = channel.allocator.buffer(capacity: 1024) buf.write(string: "hello") - + XCTAssertTrue(try channel.writeOutbound(buf)) XCTAssertTrue(try channel.finish()) XCTAssertEqual(.byteBuffer(buf), channel.readOutbound()) XCTAssertNil(channel.readOutbound()) XCTAssertNil(channel.readInbound()) } - + func testWriteInboundByteBuffer() throws { let channel = EmbeddedChannel() var buf = channel.allocator.buffer(capacity: 1024) buf.write(string: "hello") - + XCTAssertTrue(try channel.writeInbound(buf)) XCTAssertTrue(try channel.finish()) XCTAssertEqual(buf, channel.readInbound()) XCTAssertNil(channel.readInbound()) XCTAssertNil(channel.readOutbound()) } - + func testWriteInboundByteBufferReThrow() throws { let channel = EmbeddedChannel() _ = try channel.pipeline.add(handler: ExceptionThrowingInboundHandler()).wait() @@ -51,7 +51,7 @@ class EmbeddedChannelTest: XCTestCase { } XCTAssertFalse(try channel.finish()) } - + func testWriteOutboundByteBufferReThrow() throws { let channel = EmbeddedChannel() _ = try channel.pipeline.add(handler: ExceptionThrowingOutboundHandler()).wait() @@ -104,20 +104,20 @@ class EmbeddedChannelTest: XCTestCase { XCTAssertEqual(handler.currentState, .unregistered) XCTAssertFalse(channel.isActive) } - + private final class ExceptionThrowingInboundHandler : ChannelInboundHandler { typealias InboundIn = String - + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { ctx.fireErrorCaught(ChannelError.operationUnsupported) } - + } - + private final class ExceptionThrowingOutboundHandler : ChannelOutboundHandler { typealias OutboundIn = String typealias OutboundOut = Never - + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { promise!.fail(error: ChannelError.operationUnsupported) } diff --git a/Tests/NIOTests/EventLoopTest.swift b/Tests/NIOTests/EventLoopTest.swift index 0a055d3ff..c2d594aff 100644 --- a/Tests/NIOTests/EventLoopTest.swift +++ b/Tests/NIOTests/EventLoopTest.swift @@ -17,7 +17,7 @@ import Dispatch import NIOConcurrencyHelpers public class EventLoopTest : XCTestCase { - + public func testSchedule() throws { let nanos = DispatchTime.now().uptimeNanoseconds let amount: TimeAmount = .seconds(1) @@ -28,7 +28,7 @@ public class EventLoopTest : XCTestCase { let value = try eventLoopGroup.next().scheduleTask(in: amount) { return true }.futureResult.wait() - + XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= amount.nanoseconds) XCTAssertTrue(value) } @@ -67,7 +67,7 @@ public class EventLoopTest : XCTestCase { // Now we're ok. XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= longAmount.nanoseconds) } - + public func testScheduleCancelled() throws { let eventLoopGroup = MultiThreadedEventLoopGroup(numThreads: 1) defer { @@ -77,15 +77,15 @@ public class EventLoopTest : XCTestCase { let scheduled = eventLoopGroup.next().scheduleTask(in: .seconds(2)) { ran.store(true) } - + scheduled.cancel() - + let nanos = DispatchTime.now().uptimeNanoseconds let amount: TimeAmount = .seconds(2) let value = try eventLoopGroup.next().scheduleTask(in: amount) { return true }.futureResult.wait() - + XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= amount.nanoseconds) XCTAssertTrue(value) XCTAssertFalse(ran.load()) @@ -194,13 +194,13 @@ public class EventLoopTest : XCTestCase { counter += 1 } let threads: [ThreadInitializer] = [body, body] - + let group = MultiThreadedEventLoopGroup(threadInitializers: threads) - + XCTAssertEqual(2, counter) XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + public func testEventLoopPinned() throws { #if os(Linux) let body: ThreadInitializer = { t in @@ -209,13 +209,13 @@ public class EventLoopTest : XCTestCase { XCTAssertEqual(set, t.affinity) } let threads: [ThreadInitializer] = [body, body] - + let group = MultiThreadedEventLoopGroup(threadInitializers: threads) - + XCTAssertNoThrow(try group.syncShutdownGracefully()) #endif } - + public func testEventLoopPinnedCPUIdsConstructor() throws { #if os(Linux) let group = MultiThreadedEventLoopGroup(pinnedCPUIds: [0]) diff --git a/Tests/NIOTests/FileRegionTest.swift b/Tests/NIOTests/FileRegionTest.swift index 316de492c..76fc55e04 100644 --- a/Tests/NIOTests/FileRegionTest.swift +++ b/Tests/NIOTests/FileRegionTest.swift @@ -16,31 +16,31 @@ import XCTest @testable import NIO class FileRegionTest : XCTestCase { - + func testWriteFileRegion() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + let numBytes = 16 * 1024 - + var content = "" for i in 0.. Bool) throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } - + class TestWriteHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer typealias OutboundOut = ByteBuffer - + private var read = false private let writeToChannel: Bool private let assertEventFn: (IdleStateHandler.IdleStateEvent) -> Bool - + init(_ writeToChannel: Bool, _ assertEventFn: @escaping (IdleStateHandler.IdleStateEvent) -> Bool) { self.writeToChannel = writeToChannel self.assertEventFn = assertEventFn } - + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { self.read = true } @@ -64,7 +64,7 @@ class IdleStateHandlerTest : XCTestCase { XCTAssertTrue(assertEventFn(event as! IdleStateHandler.IdleStateEvent)) ctx.close(promise: nil) } - + public func channelActive(ctx: ChannelHandlerContext) { if writeToChannel { var buffer = ctx.channel.allocator.buffer(capacity: 4) @@ -73,7 +73,7 @@ class IdleStateHandlerTest : XCTestCase { } } } - + let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) .childChannelInitializer { channel in @@ -81,11 +81,11 @@ class IdleStateHandlerTest : XCTestCase { channel.pipeline.add(handler: TestWriteHandler(writeToChannel, assertEventFn)) } }.bind(host: "127.0.0.1", port: 0).wait() - + defer { _ = serverChannel.close() } - + let clientChannel = try ClientBootstrap(group: group).connect(to: serverChannel.localAddress!).wait() if !writeToChannel { var buffer = clientChannel.allocator.buffer(capacity: 4) diff --git a/Tests/NIOTests/RecvByteBufAllocatorTest.swift b/Tests/NIOTests/RecvByteBufAllocatorTest.swift index 596d16622..922696419 100644 --- a/Tests/NIOTests/RecvByteBufAllocatorTest.swift +++ b/Tests/NIOTests/RecvByteBufAllocatorTest.swift @@ -23,10 +23,10 @@ public class AdaptiveRecvByteBufferAllocatorTest : XCTestCase { func testAdaptive() throws { let buffer = adaptive.buffer(allocator: allocator) XCTAssertEqual(1024, buffer.capacity) - + testActualReadBytes(mayGrow: false, actualReadBytes: 1024, expectedCapacity: 16384) testActualReadBytes(mayGrow: true, actualReadBytes: 16384, expectedCapacity: 16384) - + // Will never go over maximum testActualReadBytes(mayGrow: true, actualReadBytes: 32768, expectedCapacity: 16384) @@ -44,20 +44,20 @@ public class AdaptiveRecvByteBufferAllocatorTest : XCTestCase { testActualReadBytes(mayGrow: false, actualReadBytes: 64, expectedCapacity: 1024) testActualReadBytes(mayGrow: false, actualReadBytes: 64, expectedCapacity: 1024) - + testActualReadBytes(mayGrow: false, actualReadBytes: 64, expectedCapacity: 512) testActualReadBytes(mayGrow: false, actualReadBytes: 64, expectedCapacity: 512) testActualReadBytes(mayGrow: false, actualReadBytes: 32, expectedCapacity: 512) testActualReadBytes(mayGrow: false, actualReadBytes: 32, expectedCapacity: 512) } - + private func testActualReadBytes(mayGrow: Bool, actualReadBytes: Int, expectedCapacity: Int) { XCTAssertEqual(mayGrow, adaptive.record(actualReadBytes: actualReadBytes)) let buffer = adaptive.buffer(allocator: allocator) XCTAssertEqual(expectedCapacity, buffer.capacity) } - + func testFixed() throws { var buffer = fixed.buffer(allocator: allocator) XCTAssertEqual(fixed.capacity, buffer.capacity) diff --git a/Tests/NIOTests/SocketChannelTest.swift b/Tests/NIOTests/SocketChannelTest.swift index 07803edbd..5f8064caf 100644 --- a/Tests/NIOTests/SocketChannelTest.swift +++ b/Tests/NIOTests/SocketChannelTest.swift @@ -35,7 +35,7 @@ public class SocketChannelTest : XCTestCase { // Create two channels with different event loops. let channelA = try ServerBootstrap(group: group).bind(host: "127.0.0.1", port: 0).wait() - let channelB: Channel = try { + let channelB: Channel = try { while true { let channel = try ServerBootstrap(group: group).bind(host: "127.0.0.1", port: 0).wait() if channel.eventLoop !== channelA.eventLoop { diff --git a/Tests/NIOTests/SystemCallWrapperHelpers.swift b/Tests/NIOTests/SystemCallWrapperHelpers.swift index 66f758ba1..317c0eb59 100644 --- a/Tests/NIOTests/SystemCallWrapperHelpers.swift +++ b/Tests/NIOTests/SystemCallWrapperHelpers.swift @@ -24,13 +24,13 @@ public func measureRunTime(_ body: () throws -> Int) rethrows -> TimeInterval { let end = Date() return end.timeIntervalSince(start) } - + _ = try measureOne(body) var measurements = Array(repeating: 0.0, count: 10) for i in 0..<10 { measurements[i] = try measureOne(body) } - + //return measurements.reduce(0, +) / 10.0 return measurements.min()! } @@ -65,15 +65,15 @@ func runSystemCallWrapperPerformanceTest(testAssertFunction: (@autoclosure () -> defer { close(fd) } - + let isDebugMode = _isDebugAssertConfiguration() if !debugModeAllowed && isDebugMode { fatalError("running in debug mode, release mode required") } - + let iterations = isDebugMode ? 100_000 : 1_000_000 let pointer = UnsafePointer(bitPattern: 0xdeadbeef)! - + let directCallTime = try measureRunTime { () -> Int in /* imitate what the system call wrappers do to have a fair comparison */ var preventCompilerOptimisation: Int = 0 @@ -100,7 +100,7 @@ func runSystemCallWrapperPerformanceTest(testAssertFunction: (@autoclosure () -> } return preventCompilerOptimisation } - + let withSystemCallWrappersTime = try measureRunTime { () -> Int in var preventCompilerOptimisation: Int = 0 for _ in 0.. } return preventCompilerOptimisation } - + let allowedOverheadPercent: Int = isDebugMode ? 1000 : 20 if allowedOverheadPercent > 100 { precondition(isDebugMode) diff --git a/Tests/NIOTests/TestUtils.swift b/Tests/NIOTests/TestUtils.swift index 94da21b6e..444cf7bed 100644 --- a/Tests/NIOTests/TestUtils.swift +++ b/Tests/NIOTests/TestUtils.swift @@ -83,32 +83,32 @@ internal extension Channel { final class ByteCountingHandler : ChannelInboundHandler { typealias InboundIn = ByteBuffer - + private let numBytes: Int private let promise: EventLoopPromise private var buffer: ByteBuffer! - + init(numBytes: Int, promise: EventLoopPromise) { self.numBytes = numBytes self.promise = promise } - + func handlerAdded(ctx: ChannelHandlerContext) { buffer = ctx.channel.allocator.buffer(capacity: numBytes) if self.numBytes == 0 { self.promise.succeed(result: buffer) } } - + func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { var currentBuffer = self.unwrapInboundIn(data) buffer.write(buffer: ¤tBuffer) - + if buffer.readableBytes == numBytes { promise.succeed(result: buffer) } } - + func assertReceived(buffer: ByteBuffer) throws { let received = try promise.futureResult.wait() XCTAssertEqual(buffer, received) diff --git a/Tests/NIOTests/TypeAssistedChannelHandlerTests.swift b/Tests/NIOTests/TypeAssistedChannelHandlerTests.swift index 54597ba65..631cae73d 100644 --- a/Tests/NIOTests/TypeAssistedChannelHandlerTests.swift +++ b/Tests/NIOTests/TypeAssistedChannelHandlerTests.swift @@ -23,7 +23,7 @@ class TypeAssistedChannelHandlerTest: XCTestCase { public typealias InboundIn = ByteBuffer public typealias InboundOut = ByteBuffer } - + // This test really just confirms that compilation works: no need to run any code. XCTAssert(true) }