webrtc/mux/
endpoint.rs

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
12/// Endpoint implements net.Conn. It is used to read muxed packets.
13pub 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    /// Close unregisters the endpoint from the Mux
23    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    /// reads a packet of len(p) bytes from the underlying conn
42    /// that are matched by the associated MuxFunc
43    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    /// writes bytes to the underlying conn
54    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}