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