Skip to main content

dope_core/io/socket/
msg.rs

1use core::ptr::{addr_of_mut, null_mut};
2
3use libc::{c_int, c_void, iovec, msghdr};
4
5#[derive(Clone, Copy, Debug)]
6#[repr(transparent)]
7pub struct IoVec {
8    raw: iovec,
9}
10
11impl IoVec {
12    #[must_use]
13    pub const fn empty() -> Self {
14        Self {
15            raw: iovec {
16                iov_base: null_mut(),
17                iov_len: 0,
18            },
19        }
20    }
21
22    #[must_use]
23    pub fn from_slice(buf: &[u8]) -> Self {
24        Self {
25            raw: iovec {
26                iov_base: buf.as_ptr() as *mut c_void,
27                iov_len: buf.len(),
28            },
29        }
30    }
31
32    #[must_use]
33    pub fn from_mut_slice(buf: &mut [u8]) -> Self {
34        Self {
35            raw: iovec {
36                iov_base: buf.as_mut_ptr() as *mut c_void,
37                iov_len: buf.len(),
38            },
39        }
40    }
41
42    #[must_use]
43    pub fn len(&self) -> usize {
44        self.raw.iov_len
45    }
46
47    #[must_use]
48    pub fn is_empty(&self) -> bool {
49        self.raw.iov_len == 0
50    }
51
52    #[must_use]
53    pub fn as_ptr(&self) -> *const u8 {
54        self.raw.iov_base as *const u8
55    }
56}
57
58#[derive(Clone, Copy, Debug)]
59#[repr(transparent)]
60pub struct MsgHdr {
61    raw: msghdr,
62}
63
64impl MsgHdr {
65    pub fn empty() -> Self {
66        Self {
67            raw: msghdr {
68                msg_name: null_mut(),
69                msg_namelen: 0,
70                msg_iov: null_mut(),
71                msg_iovlen: 0,
72                msg_control: null_mut(),
73                msg_controllen: 0,
74                msg_flags: 0,
75            },
76        }
77    }
78
79    pub fn set_name_ptr(&mut self, ptr: *mut c_void, len: u32) {
80        self.raw.msg_name = ptr;
81        self.raw.msg_namelen = len;
82    }
83
84    pub fn set_namelen(&mut self, len: u32) {
85        self.raw.msg_namelen = len;
86    }
87
88    pub fn set_iov(&mut self, iov: &[IoVec]) {
89        self.raw.msg_iov = iov.as_ptr() as *mut iovec;
90        self.raw.msg_iovlen = iov.len() as _;
91    }
92
93    pub fn set_control(&mut self, ptr: *mut c_void, len: usize) {
94        self.raw.msg_control = ptr;
95        self.raw.msg_controllen = len as _;
96    }
97
98    pub fn flags(&self) -> c_int {
99        self.raw.msg_flags
100    }
101
102    pub fn raw(&self) -> &msghdr {
103        &self.raw
104    }
105
106    pub fn as_mut_ptr(&mut self) -> *mut msghdr {
107        addr_of_mut!(self.raw)
108    }
109}