]>
Commit | Line | Data |
---|---|---|
9cffeac4 WB |
1 | //! Various utilities. |
2 | //! | |
3 | //! Note that this should stay small, otherwise we should introduce a dependency on our `proxmox` | |
4 | //! crate as that's where we have all this stuff usually... | |
5 | ||
9cffeac4 WB |
6 | use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; |
7 | ||
9aa2a15a | 8 | pub use io_uring::iovec::{IoVec, IoVecMut}; |
9cffeac4 | 9 | |
e420f6f9 WB |
10 | /// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned |
11 | /// `RawFd` is required without the corresponding handler object (such as when only the file | |
12 | /// descriptor number is required in a closure which may be dropped instead of being executed). | |
13 | #[repr(transparent)] | |
14 | pub struct Fd(pub RawFd); | |
15 | ||
16 | file_descriptor_impl!(Fd); | |
17 | ||
512f780a WB |
18 | impl FromRawFd for Fd { |
19 | unsafe fn from_raw_fd(fd: RawFd) -> Self { | |
20 | Self(fd) | |
21 | } | |
22 | } | |
23 | ||
9ebd1972 WB |
24 | impl Fd { |
25 | pub fn set_nonblocking(&self, nb: bool) -> std::io::Result<()> { | |
26 | let fd = self.as_raw_fd(); | |
27 | let flags = c_try!(unsafe { libc::fcntl(fd, libc::F_GETFL) }); | |
28 | let flags = if nb { | |
29 | flags | libc::O_NONBLOCK | |
30 | } else { | |
31 | flags & !libc::O_NONBLOCK | |
32 | }; | |
33 | c_try!(unsafe { libc::fcntl(fd, libc::F_SETFL, flags) }); | |
34 | Ok(()) | |
35 | } | |
36 | } | |
37 | ||
9cffeac4 WB |
38 | /// Byte vector utilities. |
39 | pub mod vec { | |
40 | /// Create an uninitialized byte vector of a specific size. | |
41 | /// | |
42 | /// This is just a shortcut for: | |
43 | /// ```no_run | |
44 | /// # let len = 64usize; | |
45 | /// let mut v = Vec::<u8>::with_capacity(len); | |
46 | /// unsafe { | |
47 | /// v.set_len(len); | |
48 | /// } | |
49 | /// ``` | |
92eface0 WB |
50 | /// |
51 | /// # Safety | |
52 | /// | |
53 | /// This is generally safe to call, but the contents of the vector are undefined. | |
52f50bd4 | 54 | #[inline] |
9cffeac4 WB |
55 | pub unsafe fn uninitialized(len: usize) -> Vec<u8> { |
56 | let mut out = Vec::with_capacity(len); | |
57 | out.set_len(len); | |
58 | out | |
59 | } | |
60 | } | |
571dbe03 | 61 | |
512f780a WB |
62 | pub trait FromFd { |
63 | fn from_fd(fd: Fd) -> Self; | |
64 | } | |
65 | ||
66 | impl<T: FromRawFd> FromFd for T { | |
67 | fn from_fd(fd: Fd) -> Self { | |
68 | unsafe { Self::from_raw_fd(fd.into_raw_fd()) } | |
69 | } | |
70 | } |