Skip to main content

mtorrent_utils/
split_stream.rs

1use local_async_utils::prelude::*;
2use tokio::io::{AsyncRead, AsyncWrite};
3use tokio::net::{TcpStream, tcp};
4
5/// Helper trait for efficiently splitting a stream into read and write halves.
6pub trait SplitStream: Unpin {
7    /// Associated type for the read half of the stream. These can be a non-owning
8    /// reference to avoid unnecessary heap allocations and reference counting.
9    type Ingress<'i>: AsyncRead + Unpin
10    where
11        Self: 'i;
12
13    /// Associated type for the write half of the stream. These can be a non-owning
14    /// reference to avoid unnecessary heap allocations and reference counting.
15    type Egress<'e>: AsyncWrite + Unpin
16    where
17        Self: 'e;
18
19    /// Split the stream into non-owning read and write halves.
20    fn split(&mut self) -> (Self::Ingress<'_>, Self::Egress<'_>);
21}
22
23impl SplitStream for TcpStream {
24    type Ingress<'i> = tcp::ReadHalf<'i>;
25    type Egress<'e> = tcp::WriteHalf<'e>;
26
27    fn split(&mut self) -> (Self::Ingress<'_>, Self::Egress<'_>) {
28        TcpStream::split(self)
29    }
30}
31
32impl SplitStream for local_pipe::DuplexEnd {
33    type Ingress<'i> = &'i mut local_pipe::ReadEnd;
34    type Egress<'e> = &'e mut local_pipe::WriteEnd;
35
36    fn split(&mut self) -> (Self::Ingress<'_>, Self::Egress<'_>) {
37        self.split()
38    }
39}