rama_net/stream/
socket.rs

1use std::io::Result;
2use std::net::SocketAddr;
3use std::ops::{Deref, DerefMut};
4
5/// Common information exposed by a Socket-like construct.
6///
7/// For now this is implemented for TCP and UDP, as these
8/// are the types that are relevant to Rama.
9pub trait Socket: Send + Sync + 'static {
10    /// Try to get the local address of the socket.
11    fn local_addr(&self) -> Result<SocketAddr>;
12
13    /// Try to get the remote address of the socket.
14    fn peer_addr(&self) -> Result<SocketAddr>;
15}
16
17impl Socket for std::net::TcpStream {
18    #[inline]
19    fn local_addr(&self) -> Result<SocketAddr> {
20        self.local_addr()
21    }
22
23    #[inline]
24    fn peer_addr(&self) -> Result<SocketAddr> {
25        self.peer_addr()
26    }
27}
28
29impl Socket for tokio::net::TcpStream {
30    #[inline]
31    fn local_addr(&self) -> Result<SocketAddr> {
32        self.local_addr()
33    }
34
35    #[inline]
36    fn peer_addr(&self) -> Result<SocketAddr> {
37        self.peer_addr()
38    }
39}
40
41impl Socket for std::net::UdpSocket {
42    #[inline]
43    fn local_addr(&self) -> Result<SocketAddr> {
44        self.local_addr()
45    }
46
47    #[inline]
48    fn peer_addr(&self) -> Result<SocketAddr> {
49        self.peer_addr()
50    }
51}
52
53impl Socket for tokio::net::UdpSocket {
54    #[inline]
55    fn local_addr(&self) -> Result<SocketAddr> {
56        self.local_addr()
57    }
58
59    #[inline]
60    fn peer_addr(&self) -> Result<SocketAddr> {
61        self.peer_addr()
62    }
63}
64
65#[derive(Debug, Clone)]
66/// Information about the socket on the egress end.
67pub struct ClientSocketInfo(pub SocketInfo);
68
69impl AsRef<SocketInfo> for ClientSocketInfo {
70    fn as_ref(&self) -> &SocketInfo {
71        &self.0
72    }
73}
74
75impl AsMut<SocketInfo> for ClientSocketInfo {
76    fn as_mut(&mut self) -> &mut SocketInfo {
77        &mut self.0
78    }
79}
80
81impl Deref for ClientSocketInfo {
82    type Target = SocketInfo;
83
84    fn deref(&self) -> &Self::Target {
85        &self.0
86    }
87}
88impl DerefMut for ClientSocketInfo {
89    fn deref_mut(&mut self) -> &mut Self::Target {
90        &mut self.0
91    }
92}
93
94#[derive(Debug, Clone)]
95/// Connected socket information.
96pub struct SocketInfo {
97    local_addr: Option<SocketAddr>,
98    peer_addr: SocketAddr,
99}
100
101impl SocketInfo {
102    /// Create a new `SocketInfo`.
103    pub const fn new(local_addr: Option<SocketAddr>, peer_addr: SocketAddr) -> Self {
104        Self {
105            local_addr,
106            peer_addr,
107        }
108    }
109
110    /// Get the local address of the socket.
111    pub fn local_addr(&self) -> Option<&SocketAddr> {
112        self.local_addr.as_ref()
113    }
114
115    /// Get the peer address of the socket.
116    pub fn peer_addr(&self) -> &SocketAddr {
117        &self.peer_addr
118    }
119}