trellis_net/
connection.rs

1
2// ===== Imports =====
3use std::{io::Error, net::SocketAddr};
4use bytes::BytesMut;
5use tokio::{net::TcpStream, io::{AsyncReadExt, AsyncWriteExt}};
6
7use crate::{
8  Address,
9  rw::{ReadPreReqs, WritePreReqs, Reader, Writer},
10};
11// ===================
12
13/// # Connection
14/// I/O Object for managing Tcp connections.
15/// A new connection can be created by connecting to an endpoint using `Connection::new()` constructor.
16pub struct Connection {
17  pub local_addr: Address,
18  pub peer_addr: Address,
19  stream: TcpStream,
20}
21
22impl Connection {
23  /// ## Constructor
24  /// Constructs a new `Connection` to the provided endpoint.
25  pub async fn new(to: Address) -> Result<Self, Error> {
26    let to: SocketAddr = to.into();
27    let stream = TcpStream::connect(to).await?;
28    let local_addr = stream.local_addr()?.into();
29    let peer_addr = stream.peer_addr()?.into();
30    Ok(Self { local_addr, peer_addr, stream })
31  }
32}
33
34impl TryFrom<TcpStream> for Connection {
35  type Error = Error;
36
37  fn try_from(stream: TcpStream) -> Result<Self, Self::Error> {
38    let local_addr = stream.local_addr()?.into();
39    let peer_addr = stream.peer_addr()?.into();
40    Ok(Self { local_addr, peer_addr, stream })
41  }
42}
43
44#[async_trait]
45impl ReadPreReqs for Connection {
46  async fn read(&mut self, byts: &mut BytesMut) -> Result<(), Error> {
47    self.stream.read(byts).await?;
48    Ok(())
49  }
50}
51
52#[async_trait]
53impl WritePreReqs for Connection {
54  async fn write(&mut self, byts: &mut BytesMut) -> Result<(), Error> {
55    self.stream.write(&byts[..]).await?;
56    Ok(())
57  }
58}
59
60#[async_trait]
61impl Reader for Connection {}
62#[async_trait]
63impl Writer for Connection {}