]>
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 | 24 | impl Fd { |
47a812af WB |
25 | pub fn set_nonblocking(&self, nb: bool) -> nix::Result<libc::c_int> { |
26 | use nix::fcntl; | |
27 | let mut flags = | |
28 | fcntl::OFlag::from_bits(fcntl::fcntl(self.0, fcntl::FcntlArg::F_GETFL)?).unwrap(); | |
29 | flags.set(fcntl::OFlag::O_NONBLOCK, nb); | |
30 | fcntl::fcntl(self.0, fcntl::FcntlArg::F_SETFL(flags)) | |
9ebd1972 WB |
31 | } |
32 | } | |
33 | ||
9cffeac4 WB |
34 | /// Byte vector utilities. |
35 | pub mod vec { | |
36 | /// Create an uninitialized byte vector of a specific size. | |
37 | /// | |
38 | /// This is just a shortcut for: | |
39 | /// ```no_run | |
40 | /// # let len = 64usize; | |
41 | /// let mut v = Vec::<u8>::with_capacity(len); | |
42 | /// unsafe { | |
43 | /// v.set_len(len); | |
44 | /// } | |
45 | /// ``` | |
92eface0 WB |
46 | /// |
47 | /// # Safety | |
48 | /// | |
49 | /// This is generally safe to call, but the contents of the vector are undefined. | |
52f50bd4 | 50 | #[inline] |
9cffeac4 WB |
51 | pub unsafe fn uninitialized(len: usize) -> Vec<u8> { |
52 | let mut out = Vec::with_capacity(len); | |
53 | out.set_len(len); | |
54 | out | |
55 | } | |
56 | } | |
571dbe03 | 57 | |
512f780a WB |
58 | pub trait FromFd { |
59 | fn from_fd(fd: Fd) -> Self; | |
60 | } | |
61 | ||
62 | impl<T: FromRawFd> FromFd for T { | |
63 | fn from_fd(fd: Fd) -> Self { | |
64 | unsafe { Self::from_raw_fd(fd.into_raw_fd()) } | |
65 | } | |
66 | } |