From 5705ce104aa1889dbfa3b16274e0ca6c4c291111 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Thu, 28 Dec 2017 15:37:06 +0100 Subject: [PATCH] Add Channel extension which allows to automatically wrap data into NIOAny --- Sources/NIO/Channel.swift | 34 ++++++++++++++++++++++++++++++++++ Sources/NIO/NIOAny.swift | 1 + 2 files changed, 35 insertions(+) diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index a3a906baf..49370aef0 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -152,6 +152,40 @@ 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(data: NIOAny(any)) + } + + /// Write data into the `Channel`, automatically wrapping with `NIOAny`. + /// + /// - seealso: `ChannelOutboundInvoker.write`. + public func write(_ any: T, promise: EventLoopPromise?) { + self.write(data: 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(data: NIOAny(any)) + } + + + /// Write and flush data into the `Channel`, automatically wrapping with `NIOAny`. + /// + /// - seealso: `ChannelOutboundInvoker.writeAndFlush`. + public func writeAndFlush(_ any: T, promise: EventLoopPromise?) { + self.writeAndFlush(data: NIOAny(any), promise: promise) + } +} + /// An error that can occur on `Channel` operations. public enum ChannelError: Error { /// Tried to connect on a `Channel` that is already connecting. diff --git a/Sources/NIO/NIOAny.swift b/Sources/NIO/NIOAny.swift index 2b18ba9a9..e2845a2c5 100644 --- a/Sources/NIO/NIOAny.swift +++ b/Sources/NIO/NIOAny.swift @@ -68,6 +68,7 @@ public struct NIOAny { case let value as AddressedEnvelope: self = .bufferEnvelope(value) default: + assert(!(value is NIOAny)) self = .other(value) } }