trellis_net/
lib.rs

1
2// ===== Imports =====
3#[macro_use] extern crate async_trait;
4use std::net::{SocketAddr, IpAddr, Ipv4Addr};
5
6use bytes::{BytesMut, BufMut};
7// ===================
8
9pub mod listener;
10pub mod connection;
11pub mod rw;
12pub mod prelude;
13
14/// # Address
15/// A utility struct for representing Socket-Addresses.
16#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
17pub struct Address {
18  /// Host
19  pub host: (u8, u8, u8, u8),
20  /// Port
21  pub port: u16,
22}
23
24impl Address {
25  /// ## Constructor
26  /// Constructs a new instance of `Address`
27  pub fn new(host: (u8, u8, u8, u8), port: u16) -> Self {
28    Self { host, port }
29  }
30}
31
32// Converts `Address` to `std::net::SocketAddr`
33impl Into<SocketAddr> for Address {
34  fn into(self) -> SocketAddr {
35    let host = IpAddr::V4(Ipv4Addr::new(self.host.0, self.host.1, self.host.2, self.host.3));
36    SocketAddr::new(host, self.port)
37  }
38}
39
40// Converts `std::net::SocketAddr` to `Address`
41impl From<SocketAddr> for Address {
42  fn from(addr: SocketAddr) -> Self {
43    if let IpAddr::V4(v4_addr) = addr.ip() {
44      let host_octets = v4_addr.octets();
45      let host = (host_octets[0], host_octets[1], host_octets[2], host_octets[3]);
46      return Self { host, port: addr.port() }
47    } else {
48      panic!("Expected an IpV4 Socket Address")
49    }
50  }
51}
52
53/// # Zero-Filled-BytesMut
54/// Helper function which returns a `BytesMut` of provided length with only zeroes.
55pub fn zero_filled_bytes_mut(len: usize) -> BytesMut {
56  let mut byts = BytesMut::with_capacity(len);
57  byts.put(&*vec![0; len]);
58  byts
59}