Skip to main content

tungstenite_get_stream/
lib.rs

1//! Convenience trait method to match on a `tungstenite::MaybeTlsStream<S>` and
2//! get the underlying stream (usually `std::net::TcpStream`).
3//!
4//! Note that `native-tls` or `rustls-tls` method must be enabled on this crate
5//! to access a TLS-enabled stream otherwise the methods will panic.
6
7use std;
8use tungstenite::stream::MaybeTlsStream;
9use tungstenite::WebSocket;
10
11pub trait GetStream <S> {
12  fn get_stream (&self) -> &S;
13  fn get_stream_mut (&mut self) -> &mut S;
14}
15
16impl <S> GetStream <S> for MaybeTlsStream <S> where
17  S : std::io::Read + std::io::Write
18{
19  fn get_stream (&self) -> &S {
20    match self {
21      MaybeTlsStream::Plain (s) => s,
22      #[cfg(feature = "native-tls")]
23      MaybeTlsStream::NativeTls (s) => s.get_ref(),
24      #[cfg(feature = "rustls-tls")]
25      MaybeTlsStream::Rustls (s) => &s.sock,
26      _ => unimplemented!(
27        "did you forget to enable native-tls or rustls-tls feature?")
28    }
29  }
30  fn get_stream_mut (&mut self) -> &mut S {
31    match self {
32      MaybeTlsStream::Plain (s) => s,
33      #[cfg(feature = "native-tls")]
34      MaybeTlsStream::NativeTls (s) => s.get_mut(),
35      #[cfg(feature = "rustls-tls")]
36      MaybeTlsStream::Rustls (s) => &mut s.sock,
37      _ => unimplemented!(
38        "did you forget to enable native-tls or rustls-tls feature?")
39    }
40  }
41}
42
43impl <S> GetStream <S> for WebSocket <MaybeTlsStream <S>> where
44  S : std::io::Read + std::io::Write
45{
46  fn get_stream (&self) -> &S {
47    self.get_ref().get_stream()
48  }
49
50  fn get_stream_mut (&mut self) -> &mut S {
51    self.get_mut().get_stream_mut()
52  }
53}