1use std::collections::HashMap;
2use std::io;
3use std::net::SocketAddr;
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use tokio::sync::Mutex;
8use util::{Buffer, Conn};
9
10use crate::mux::mux_func::MatchFunc;
11
12pub struct Endpoint {
14 pub(crate) id: usize,
15 pub(crate) buffer: Buffer,
16 pub(crate) match_fn: MatchFunc,
17 pub(crate) next_conn: Arc<dyn Conn + Send + Sync>,
18 pub(crate) endpoints: Arc<Mutex<HashMap<usize, Arc<Endpoint>>>>,
19}
20
21impl Endpoint {
22 pub async fn close(&self) -> Result<()> {
24 self.buffer.close().await;
25
26 let mut endpoints = self.endpoints.lock().await;
27 endpoints.remove(&self.id);
28
29 Ok(())
30 }
31}
32
33type Result<T> = std::result::Result<T, util::Error>;
34
35#[async_trait]
36impl Conn for Endpoint {
37 async fn connect(&self, _addr: SocketAddr) -> Result<()> {
38 Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
39 }
40
41 async fn recv(&self, buf: &mut [u8]) -> Result<usize> {
44 match self.buffer.read(buf, None).await {
45 Ok(n) => Ok(n),
46 Err(err) => Err(io::Error::new(io::ErrorKind::Other, err.to_string()).into()),
47 }
48 }
49 async fn recv_from(&self, _buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
50 Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
51 }
52
53 async fn send(&self, buf: &[u8]) -> Result<usize> {
55 self.next_conn.send(buf).await
56 }
57
58 async fn send_to(&self, _buf: &[u8], _target: SocketAddr) -> Result<usize> {
59 Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
60 }
61
62 fn local_addr(&self) -> Result<SocketAddr> {
63 self.next_conn.local_addr()
64 }
65
66 fn remote_addr(&self) -> Option<SocketAddr> {
67 self.next_conn.remote_addr()
68 }
69
70 async fn close(&self) -> Result<()> {
71 self.next_conn.close().await
72 }
73
74 fn as_any(&self) -> &(dyn std::any::Any + Send + Sync) {
75 self
76 }
77}