tcp_channel_server/
builder.rs1use crate::{ConnectEventType, TCPPeer, TCPServer};
2use aqueue::Actor;
3use std::future::Future;
4use std::marker::PhantomData;
5use std::sync::Arc;
6use tokio::io::{AsyncRead, AsyncWrite, ReadHalf};
7use tokio::net::{TcpStream, ToSocketAddrs};
8
9pub struct Builder<I, R, A, T, B, C, IST> {
11 input: Option<I>,
12 connect_event: Option<ConnectEventType>,
13 stream_init: Option<IST>,
14 addr: A,
15 _phantom1: PhantomData<R>,
16 _phantom2: PhantomData<T>,
17 _phantom3: PhantomData<C>,
18 _phantom4: PhantomData<B>,
19}
20
21impl<I, R, A, T, B, C, IST> Builder<I, R, A, T, B, C, IST>
22where
23 I: Fn(ReadHalf<C>, Arc<TCPPeer<C>>, T) -> R + Send + Sync + Clone + 'static,
24 R: Future<Output = anyhow::Result<()>> + Send + 'static,
25 A: ToSocketAddrs,
26 T: Clone + Send + 'static,
27 B: Future<Output = anyhow::Result<C>> + Send + 'static,
28 C: AsyncRead + AsyncWrite + Send + Sync + 'static,
29 IST: Fn(TcpStream) -> B + Send + Sync + 'static,
30{
31 pub fn new(addr: A) -> Builder<I, R, A, T, B, C, IST> {
32 Builder {
33 input: None,
34 connect_event: None,
35 stream_init: None,
36 addr,
37 _phantom1: Default::default(),
38 _phantom2: Default::default(),
39 _phantom3: Default::default(),
40 _phantom4: Default::default(),
41 }
42 }
43
44 pub fn set_input_event(mut self, f: I) -> Self {
46 self.input = Some(f);
47 self
48 }
49
50 pub fn set_connect_event(mut self, c: ConnectEventType) -> Self {
52 self.connect_event = Some(c);
53 self
54 }
55
56 pub fn set_stream_init(mut self, c: IST) -> Self {
58 self.stream_init = Some(c);
59 self
60 }
61
62 pub async fn build(mut self) -> Arc<Actor<TCPServer<I, R, T, B, C, IST>>> {
64 if let Some(input) = self.input.take() {
65 if let Some(stream_init) = self.stream_init.take() {
66 return if let Some(connect) = self.connect_event.take() {
67 TCPServer::new(self.addr, stream_init, input, Some(connect))
68 .await
69 .unwrap()
70 } else {
71 TCPServer::new(self.addr, stream_init, input, None)
72 .await
73 .unwrap()
74 };
75 }
76 panic!("stream_init is no settings,please use set_stream_init function.");
77 }
78 panic!("input event is no settings,please use set_input_event function set input event.");
79 }
80}