|
| 1 | +use std::io; |
| 2 | +use std::ops::Deref; |
| 3 | +use std::result::Result as StdResult; |
| 4 | + |
| 5 | +use mlua::{Lua, Result, String as LuaString, Table, UserData, UserDataMethods, UserDataRegistry, Value}; |
| 6 | + |
| 7 | +use crate::net::{AddressProvider, AnySocketAddr}; |
| 8 | +use crate::time::Duration; |
| 9 | + |
| 10 | +/// UDP socket wrapper. |
| 11 | +pub struct UdpSocket { |
| 12 | + pub(crate) socket: tokio::net::UdpSocket, |
| 13 | + pub(crate) recv_timeout: Option<Duration>, |
| 14 | +} |
| 15 | + |
| 16 | +impl Deref for UdpSocket { |
| 17 | + type Target = tokio::net::UdpSocket; |
| 18 | + |
| 19 | + #[inline] |
| 20 | + fn deref(&self) -> &Self::Target { |
| 21 | + &self.socket |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +impl From<tokio::net::UdpSocket> for UdpSocket { |
| 26 | + fn from(socket: tokio::net::UdpSocket) -> Self { |
| 27 | + UdpSocket { |
| 28 | + socket, |
| 29 | + recv_timeout: None, |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl AddressProvider for UdpSocket { |
| 35 | + fn local_addr(&self) -> io::Result<AnySocketAddr> { |
| 36 | + self.socket.local_addr().map(AnySocketAddr::IP) |
| 37 | + } |
| 38 | + |
| 39 | + fn peer_addr(&self) -> io::Result<AnySocketAddr> { |
| 40 | + self.socket.peer_addr().map(AnySocketAddr::IP) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl UserData for UdpSocket { |
| 45 | + fn register(registry: &mut UserDataRegistry<Self>) { |
| 46 | + registry.add_async_function("bind", bind); |
| 47 | + |
| 48 | + registry.add_method("local_addr", |_, this, ()| Ok(this.local_addr()?)); |
| 49 | + registry.add_method("peer_addr", |_, this, ()| Ok(this.peer_addr()?)); |
| 50 | + |
| 51 | + registry.add_method_mut("set_recv_timeout", |_, this, dur: Option<Duration>| { |
| 52 | + this.recv_timeout = dur; |
| 53 | + Ok(()) |
| 54 | + }); |
| 55 | + |
| 56 | + registry.add_method("set_ttl", |_, this, ttl: u32| { |
| 57 | + lua_try!(this.socket.set_ttl(ttl)); |
| 58 | + Ok(Ok(())) |
| 59 | + }); |
| 60 | + |
| 61 | + registry.add_method("ttl", |_, this, ()| { |
| 62 | + let ttl = lua_try!(this.socket.ttl()); |
| 63 | + Ok(Ok(ttl)) |
| 64 | + }); |
| 65 | + |
| 66 | + registry.add_async_method("connect", |_, this, (host, port): (String, u16)| async move { |
| 67 | + lua_try!(this.socket.connect((host, port)).await); |
| 68 | + Ok(Ok(true)) |
| 69 | + }); |
| 70 | + |
| 71 | + registry.add_async_method_mut("send", |_, this, data: LuaString| async move { |
| 72 | + let n = lua_try!(this.socket.send(&data.as_bytes()).await); |
| 73 | + Ok(Ok(n)) |
| 74 | + }); |
| 75 | + |
| 76 | + registry.add_async_method_mut("recv", |lua, this, size: Option<usize>| async move { |
| 77 | + let size = size.unwrap_or(1472); // Default MTU size minus UDP header |
| 78 | + let mut buf = vec![0; size]; // TODO: reuse buffer? |
| 79 | + let n = with_io_timeout!(this.recv_timeout, this.socket.recv(&mut buf)); |
| 80 | + let n = lua_try!(n); |
| 81 | + buf.truncate(n); |
| 82 | + Ok(Ok(lua.create_string(buf)?)) |
| 83 | + }); |
| 84 | + |
| 85 | + registry.add_async_method_mut( |
| 86 | + "send_to", |
| 87 | + |_, this, (data, host, port): (LuaString, String, u16)| async move { |
| 88 | + let n = lua_try!(this.socket.send_to(&data.as_bytes(), (host, port)).await); |
| 89 | + Ok(Ok(n)) |
| 90 | + }, |
| 91 | + ); |
| 92 | + |
| 93 | + registry.add_async_method_mut("recv_from", |lua, this, size: Option<usize>| async move { |
| 94 | + let size = size.unwrap_or(1472); // Default MTU size minus UDP header |
| 95 | + let mut buf = vec![0; size]; // TODO: reuse buffer? |
| 96 | + match with_io_timeout!(this.recv_timeout, this.socket.recv_from(&mut buf)) { |
| 97 | + Ok((n, addr)) => { |
| 98 | + buf.truncate(n); |
| 99 | + let data = lua.create_string(buf)?; |
| 100 | + Ok((Value::String(data), addr.to_string())) |
| 101 | + } |
| 102 | + Err(e) => Ok((Value::Nil, e.to_string())), |
| 103 | + } |
| 104 | + }); |
| 105 | + |
| 106 | + registry.add_method("set_broadcast", |_, this, enable: bool| { |
| 107 | + lua_try!(this.socket.set_broadcast(enable)); |
| 108 | + Ok(Ok(true)) |
| 109 | + }); |
| 110 | + |
| 111 | + registry.add_method("broadcast", |_, this, ()| { |
| 112 | + let enabled = lua_try!(this.socket.broadcast()); |
| 113 | + Ok(Ok(enabled)) |
| 114 | + }); |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +/// Binds a UDP socket to the given host and port with optional parameters. |
| 119 | +pub async fn bind( |
| 120 | + _: Lua, |
| 121 | + (host, port, params): (String, Option<u16>, Option<Table>), |
| 122 | +) -> Result<StdResult<UdpSocket, String>> { |
| 123 | + let port = port.unwrap_or(0); |
| 124 | + let recv_timeout = opt_param!(Duration, params, "recv_timeout")?; |
| 125 | + |
| 126 | + let socket = lua_try!(tokio::net::UdpSocket::bind((host, port)).await); |
| 127 | + |
| 128 | + Ok(Ok(UdpSocket { socket, recv_timeout })) |
| 129 | +} |
0 commit comments