ssilide/lib.rs
1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use std::io;
5use std::net;
6
7pub struct Interface {
8 addr: net::SocketAddr,
9}
10
11impl Interface {
12 const IP: net::IpAddr = net::IpAddr::V4(net::Ipv4Addr::LOCALHOST);
13
14 /// Declare a new interface.
15 ///
16 /// ```
17 /// const INTERFACE: ssilide::Interface = ssilide::Interface::new(43615);
18 /// ```
19 pub const fn new(port: u16) -> Self {
20 Self { addr: net::SocketAddr::new(Self::IP, port) }
21 }
22
23 /// Claim this interface.
24 ///
25 /// ```
26 /// const INTERFACE: ssilide::Interface = ssilide::Interface::new(43615);
27 /// let claim = INTERFACE.claim().expect("interface already claimed");
28 /// ```
29 pub fn claim(&self) -> io::Result<net::UdpSocket> {
30 net::UdpSocket::bind(self.addr)
31 }
32
33 /// Connect to this interface.
34 ///
35 /// ```
36 /// const INTERFACE: ssilide::Interface = ssilide::Interface::new(43615);
37 /// let client = INTERFACE.connect().expect("interface not claimed");
38 /// ```
39 pub fn connect(&self) -> io::Result<net::UdpSocket> {
40 net::UdpSocket::bind(net::SocketAddr::new(Self::IP, 0))
41 .and_then(|socket| socket.connect(self.addr).map(|()| socket))
42 }
43}