Skip to main content

socks5_impl/
stream.rs

1use std::io::{Read, Write};
2
3pub trait StreamOperation {
4    fn retrieve_from_stream<R>(stream: &mut R) -> std::io::Result<Self>
5    where
6        R: Read,
7        Self: Sized;
8
9    fn write_to_stream<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
10        let mut buffer = bytes::BytesMut::with_capacity(self.len());
11        self.write_to_buf(&mut buffer);
12        writer.write_all(&buffer)
13    }
14
15    fn write_to_buf<B: bytes::BufMut>(&self, buffer: &mut B);
16
17    fn len(&self) -> usize;
18
19    fn is_empty(&self) -> bool {
20        self.len() == 0
21    }
22}
23
24#[cfg(feature = "tokio")]
25#[async_trait::async_trait]
26pub trait AsyncStreamOperation: StreamOperation {
27    async fn retrieve_from_async_stream<R>(reader: &mut R) -> std::io::Result<Self>
28    where
29        R: tokio::io::AsyncRead + Unpin + Send + ?Sized,
30        Self: Sized;
31
32    async fn write_to_async_stream<W>(&self, writer: &mut W) -> std::io::Result<()>
33    where
34        W: tokio::io::AsyncWrite + Unpin + Send + ?Sized,
35    {
36        use tokio::io::AsyncWriteExt;
37
38        let mut buffer = bytes::BytesMut::with_capacity(self.len());
39        self.write_to_buf(&mut buffer);
40        writer.write_all(&buffer).await
41    }
42}