aboutsummaryrefslogtreecommitdiff
path: root/net/src/transports/udp.rs
blob: a8b505c58f45f1245b6d2680377cef4d9fb46d25 (plain)
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
use std::net::SocketAddr;

use async_trait::async_trait;
use smol::net::UdpSocket;

use crate::{
    connection::{Connection, ToConn},
    endpoint::{Addr, Endpoint, Port},
    Error, Result,
};

/// UDP network connection implementation of the [`Connection`] trait.
pub struct UdpConn {
    inner: UdpSocket,
}

impl UdpConn {
    /// Creates a new UdpConn
    pub fn new(conn: UdpSocket) -> Self {
        Self { inner: conn }
    }
}

impl UdpConn {
    /// Receives a single datagram message. Returns the number of bytes read
    /// and the origin endpoint.
    pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, Endpoint)> {
        let (size, addr) = self.inner.recv_from(buf).await?;
        Ok((size, Endpoint::new_udp_addr(&addr)))
    }

    /// Sends data to the given address. Returns the number of bytes written.
    pub async fn send_to(&self, buf: &[u8], addr: &Endpoint) -> Result<usize> {
        let addr: SocketAddr = addr.clone().try_into()?;
        let size = self.inner.send_to(buf, addr).await?;
        Ok(size)
    }
}

#[async_trait]
impl Connection for UdpConn {
    fn peer_endpoint(&self) -> Result<Endpoint> {
        Ok(Endpoint::new_udp_addr(&self.inner.peer_addr()?))
    }

    fn local_endpoint(&self) -> Result<Endpoint> {
        Ok(Endpoint::new_udp_addr(&self.inner.local_addr()?))
    }

    async fn read(&self, buf: &mut [u8]) -> Result<usize> {
        self.inner.recv(buf).await.map_err(Error::from)
    }

    async fn write(&self, buf: &[u8]) -> Result<usize> {
        self.inner.send(buf).await.map_err(Error::from)
    }
}

/// Connects to the given UDP address and port.
pub async fn dial_udp(addr: &Addr, port: &Port) -> Result<UdpConn> {
    let address = format!("{}:{}", addr, port);

    // Let the operating system assign an available port to this socket
    let conn = UdpSocket::bind("[::]:0").await?;
    conn.connect(address).await?;
    Ok(UdpConn::new(conn))
}

/// Listens on the given UDP address and port.
pub async fn listen_udp(addr: &Addr, port: &Port) -> Result<UdpConn> {
    let address = format!("{}:{}", addr, port);
    let conn = UdpSocket::bind(address).await?;
    let udp_conn = UdpConn::new(conn);
    Ok(udp_conn)
}

impl From<UdpSocket> for Box<dyn Connection> {
    fn from(conn: UdpSocket) -> Self {
        Box::new(UdpConn::new(conn))
    }
}

impl ToConn for UdpSocket {
    fn to_conn(self) -> Box<dyn Connection> {
        self.into()
    }
}

impl ToConn for UdpConn {
    fn to_conn(self) -> Box<dyn Connection> {
        Box::new(self)
    }
}