deribit_fix/model/
stream.rs

1/******************************************************************************
2   Author: Joaquín Béjar García
3   Email: jb@taunais.com
4   Date: 21/7/25
5******************************************************************************/
6use tokio::io::{AsyncReadExt, AsyncWriteExt};
7use tokio::net::TcpStream;
8use tokio_native_tls::TlsStream;
9
10/// Connection wrapper for both TCP and TLS streams
11pub enum Stream {
12    /// Plain TCP stream
13    Tcp(TcpStream),
14    /// TLS encrypted stream
15    Tls(TlsStream<TcpStream>),
16}
17
18impl Stream {
19    /// Read data from the stream
20    pub async fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
21        match self {
22            Stream::Tcp(stream) => stream.read(buf).await,
23            Stream::Tls(stream) => stream.read(buf).await,
24        }
25    }
26
27    /// Write all data to the stream
28    pub async fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
29        match self {
30            Stream::Tcp(stream) => stream.write_all(buf).await,
31            Stream::Tls(stream) => stream.write_all(buf).await,
32        }
33    }
34
35    /// Flush the stream
36    pub async fn flush(&mut self) -> std::io::Result<()> {
37        match self {
38            Stream::Tcp(stream) => stream.flush().await,
39            Stream::Tls(stream) => stream.flush().await,
40        }
41    }
42
43    /// Shutdown the stream
44    pub async fn shutdown(&mut self) -> std::io::Result<()> {
45        match self {
46            Stream::Tcp(stream) => stream.shutdown().await,
47            Stream::Tls(stream) => stream.shutdown().await,
48        }
49    }
50}