tungstenite-get-stream 0.1.0

Convenience trait method to get underlying stream
Documentation
//! Convenience trait method to match on a `tungstenite::MaybeTlsStream<S>` and
//! get the underlying stream (usually `std::net::TcpStream`).
//!
//! Note that `native-tls` or `rustls-tls` method must be enabled on this crate
//! to access a TLS-enabled stream otherwise the methods will panic.

use std;
use tungstenite::stream::MaybeTlsStream;
use tungstenite::WebSocket;

pub trait GetStream <S> {
  fn get_stream (&self) -> &S;
  fn get_stream_mut (&mut self) -> &mut S;
}

impl <S> GetStream <S> for MaybeTlsStream <S> where
  S : std::io::Read + std::io::Write
{
  fn get_stream (&self) -> &S {
    match self {
      MaybeTlsStream::Plain (s) => s,
      #[cfg(feature = "native-tls")]
      MaybeTlsStream::NativeTls (s) => s.get_ref(),
      #[cfg(feature = "rustls-tls")]
      MaybeTlsStream::Rustls (s) => &s.sock,
      _ => unimplemented!(
        "did you forget to enable native-tls or rustls-tls feature?")
    }
  }
  fn get_stream_mut (&mut self) -> &mut S {
    match self {
      MaybeTlsStream::Plain (s) => s,
      #[cfg(feature = "native-tls")]
      MaybeTlsStream::NativeTls (s) => s.get_mut(),
      #[cfg(feature = "rustls-tls")]
      MaybeTlsStream::Rustls (s) => &mut s.sock,
      _ => unimplemented!(
        "did you forget to enable native-tls or rustls-tls feature?")
    }
  }
}

impl <S> GetStream <S> for WebSocket <MaybeTlsStream <S>> where
  S : std::io::Read + std::io::Write
{
  fn get_stream (&self) -> &S {
    self.get_ref().get_stream()
  }

  fn get_stream_mut (&mut self) -> &mut S {
    self.get_mut().get_stream_mut()
  }
}