nex_sys/
lib.rs

1//! Cross-platform system helpers and low-level wrappers used internally by the nex crates.
2
3#[cfg(not(target_os = "windows"))]
4mod unix;
5#[cfg(not(target_os = "windows"))]
6pub use self::unix::*;
7
8#[cfg(target_os = "windows")]
9mod windows;
10#[cfg(target_os = "windows")]
11pub use self::windows::*;
12
13/// Any file descriptor on unix, only sockets on Windows.
14pub struct FileDesc {
15    pub fd: CSocket,
16}
17
18impl Drop for FileDesc {
19    fn drop(&mut self) {
20        unsafe {
21            close(self.fd);
22        }
23    }
24}
25
26/// Sends data to a socket, returning the number of bytes sent.
27pub fn send_to(
28    socket: CSocket,
29    buffer: &[u8],
30    dst: *const SockAddr,
31    slen: SockLen,
32) -> std::io::Result<usize> {
33    let send_len = retry(&mut || unsafe {
34        sendto(
35            socket,
36            buffer.as_ptr() as Buf,
37            buffer.len() as BufLen,
38            0,
39            dst,
40            slen,
41        )
42    });
43
44    if send_len < 0 {
45        Err(std::io::Error::last_os_error())
46    } else {
47        Ok(send_len as usize)
48    }
49}
50
51/// Receives data from a socket, returning the number of bytes read.
52pub fn recv_from(
53    socket: CSocket,
54    buffer: &mut [u8],
55    caddr: *mut SockAddrStorage,
56) -> std::io::Result<usize> {
57    let mut caddrlen = std::mem::size_of::<SockAddrStorage>() as SockLen;
58    let len = retry(&mut || unsafe {
59        recvfrom(
60            socket,
61            buffer.as_ptr() as MutBuf,
62            buffer.len() as BufLen,
63            0,
64            caddr as *mut SockAddr,
65            &mut caddrlen,
66        )
67    });
68
69    if len < 0 {
70        Err(std::io::Error::last_os_error())
71    } else {
72        Ok(len as usize)
73    }
74}