From 72ca8433f574f8d70fc66aa6856affdf773a5867 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 28 Nov 2014 15:43:58 -0800 Subject: [PATCH] Add MaybeSslStream --- src/ssl/mod.rs | 74 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/src/ssl/mod.rs b/src/ssl/mod.rs index c9e33e8e4..778b50c7e 100644 --- a/src/ssl/mod.rs +++ b/src/ssl/mod.rs @@ -436,12 +436,29 @@ impl SslStream { SslStream::new_server_from(ssl, stream) } - /// Returns a mutable reference to the underlying stream + /// Returns a mutable reference to the underlying stream. /// /// ## Warning + /// /// `read`ing or `write`ing directly to the underlying stream will most /// likely desynchronize the SSL session. + #[deprecated="use get_mut instead"] pub fn get_inner(&mut self) -> &mut S { + self.get_mut() + } + + /// Returns a reference to the underlying stream. + pub fn get_ref(&self) -> &S { + &self.stream + } + + /// Returns a mutable reference to the underlying stream. + /// + /// ## Warning + /// + /// It is inadvisable to read from or write to the underlying stream as it + /// will most likely desynchronize the SSL session. + pub fn get_mut(&mut self) -> &mut S { &mut self.stream } @@ -530,3 +547,58 @@ impl Writer for SslStream { self.stream.flush() } } + +/// A utility type to help in cases where the use of SSL is decided at runtime. +pub enum MaybeSslStream where S: Stream { + /// A connection using SSL + Ssl(SslStream), + /// A connection not using SSL + Normal(S), +} + +impl Reader for MaybeSslStream where S: Stream { + fn read(&mut self, buf: &mut [u8]) -> IoResult { + match *self { + MaybeSslStream::Ssl(ref mut s) => s.read(buf), + MaybeSslStream::Normal(ref mut s) => s.read(buf), + } + } +} + +impl Writer for MaybeSslStream where S: Stream{ + fn write(&mut self, buf: &[u8]) -> IoResult<()> { + match *self { + MaybeSslStream::Ssl(ref mut s) => s.write(buf), + MaybeSslStream::Normal(ref mut s) => s.write(buf), + } + } + + fn flush(&mut self) -> IoResult<()> { + match *self { + MaybeSslStream::Ssl(ref mut s) => s.flush(), + MaybeSslStream::Normal(ref mut s) => s.flush(), + } + } +} + +impl MaybeSslStream where S: Stream { + /// Returns a reference to the underlying stream. + pub fn get_ref(&self) -> &S { + match *self { + MaybeSslStream::Ssl(ref s) => s.get_ref(), + MaybeSslStream::Normal(ref s) => s, + } + } + + /// Returns a mutable reference to the underlying stream. + /// + /// ## Warning + /// + /// It is inadvisable to read from or write to the underlying stream. + pub fn get_mut(&mut self) -> &mut S { + match *self { + MaybeSslStream::Ssl(ref mut s) => s.get_mut(), + MaybeSslStream::Normal(ref mut s) => s, + } + } +} -- GitLab