rd_interface/
interface.rs1use std::net::SocketAddr;
2
3pub use crate::Context;
4pub use crate::{Address, Error, Result};
5pub use async_trait::async_trait;
6pub use std::sync::Arc;
7pub use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
8
9pub trait IntoDyn<DynType> {
10 fn into_dyn(self) -> DynType
11 where
12 Self: Sized + 'static;
13}
14
15#[async_trait]
17pub trait ITcpListener: Unpin + Send + Sync {
18 async fn accept(&self) -> Result<(TcpStream, SocketAddr)>;
19 async fn local_addr(&self) -> Result<SocketAddr>;
20}
21pub type TcpListener = Box<dyn ITcpListener>;
22
23impl<T: ITcpListener> IntoDyn<TcpListener> for T {
24 fn into_dyn(self) -> TcpListener
25 where
26 Self: Sized + 'static,
27 {
28 Box::new(self)
29 }
30}
31
32#[async_trait]
34pub trait ITcpStream: AsyncRead + AsyncWrite + Unpin + Send + Sync {
35 async fn peer_addr(&self) -> Result<SocketAddr>;
36 async fn local_addr(&self) -> Result<SocketAddr>;
37}
38pub type TcpStream = Box<dyn ITcpStream>;
39
40impl<T: ITcpStream> IntoDyn<TcpStream> for T {
41 fn into_dyn(self) -> TcpStream
42 where
43 Self: Sized + 'static,
44 {
45 Box::new(self)
46 }
47}
48
49#[async_trait]
51pub trait IUdpSocket: Unpin + Send + Sync {
52 async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>;
53 async fn send_to(&self, buf: &[u8], addr: Address) -> Result<usize>;
54 async fn local_addr(&self) -> Result<SocketAddr>;
55}
56pub type UdpSocket = Arc<dyn IUdpSocket>;
57
58impl<T: IUdpSocket> IntoDyn<UdpSocket> for T {
59 fn into_dyn(self) -> UdpSocket
60 where
61 Self: Sized + 'static,
62 {
63 Arc::new(self)
64 }
65}
66
67#[async_trait]
69pub trait INet: Unpin + Send + Sync {
70 async fn tcp_connect(&self, ctx: &mut Context, addr: Address) -> Result<TcpStream>;
71 async fn tcp_bind(&self, ctx: &mut Context, addr: Address) -> Result<TcpListener>;
72 async fn udp_bind(&self, ctx: &mut Context, addr: Address) -> Result<UdpSocket>;
73}
74pub type Net = Arc<dyn INet>;
75
76impl<T: INet> IntoDyn<Net> for T {
77 fn into_dyn(self) -> Net
78 where
79 Self: Sized + 'static,
80 {
81 Arc::new(self)
82 }
83}
84
85#[async_trait]
87pub trait IServer: Unpin + Send + Sync {
88 async fn start(&self) -> Result<()>;
89}
90pub type Server = Box<dyn IServer>;
91
92impl<T: IServer> IntoDyn<Server> for T {
93 fn into_dyn(self) -> Server
94 where
95 Self: Sized + 'static,
96 {
97 Box::new(self)
98 }
99}
100
101#[async_trait]
103pub trait IUdpChannel: Send + Sync {
104 async fn recv_send_to(&self, data: &mut [u8]) -> Result<(usize, Address)>;
105 async fn send_recv_from(&self, data: &[u8], addr: SocketAddr) -> Result<usize>;
106}
107pub type UdpChannel = Arc<dyn IUdpChannel>;
108
109impl<T: IUdpChannel> crate::IntoDyn<UdpChannel> for T {
110 fn into_dyn(self) -> UdpChannel
111 where
112 Self: Sized + 'static,
113 {
114 Arc::new(self)
115 }
116}