]>
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 | ||
e420f6f9 WB |
8 | /// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned |
9 | /// `RawFd` is required without the corresponding handler object (such as when only the file | |
10 | /// descriptor number is required in a closure which may be dropped instead of being executed). | |
11 | #[repr(transparent)] | |
12 | pub struct Fd(pub RawFd); | |
13 | ||
14 | file_descriptor_impl!(Fd); | |
15 | ||
512f780a WB |
16 | impl FromRawFd for Fd { |
17 | unsafe fn from_raw_fd(fd: RawFd) -> Self { | |
18 | Self(fd) | |
19 | } | |
20 | } | |
21 | ||
9ebd1972 | 22 | impl Fd { |
1282264a | 23 | pub fn set_nonblocking(&mut self, nb: bool) -> nix::Result<libc::c_int> { |
47a812af WB |
24 | use nix::fcntl; |
25 | let mut flags = | |
26 | fcntl::OFlag::from_bits(fcntl::fcntl(self.0, fcntl::FcntlArg::F_GETFL)?).unwrap(); | |
27 | flags.set(fcntl::OFlag::O_NONBLOCK, nb); | |
28 | fcntl::fcntl(self.0, fcntl::FcntlArg::F_SETFL(flags)) | |
9ebd1972 WB |
29 | } |
30 | } | |
31 | ||
9cffeac4 WB |
32 | /// Byte vector utilities. |
33 | pub mod vec { | |
34 | /// Create an uninitialized byte vector of a specific size. | |
35 | /// | |
36 | /// This is just a shortcut for: | |
37 | /// ```no_run | |
38 | /// # let len = 64usize; | |
39 | /// let mut v = Vec::<u8>::with_capacity(len); | |
40 | /// unsafe { | |
41 | /// v.set_len(len); | |
42 | /// } | |
43 | /// ``` | |
92eface0 WB |
44 | /// |
45 | /// # Safety | |
46 | /// | |
47 | /// This is generally safe to call, but the contents of the vector are undefined. | |
52f50bd4 | 48 | #[inline] |
9cffeac4 WB |
49 | pub unsafe fn uninitialized(len: usize) -> Vec<u8> { |
50 | let mut out = Vec::with_capacity(len); | |
51 | out.set_len(len); | |
52 | out | |
53 | } | |
54 | } | |
571dbe03 | 55 | |
512f780a WB |
56 | pub trait FromFd { |
57 | fn from_fd(fd: Fd) -> Self; | |
58 | } | |
59 | ||
60 | impl<T: FromRawFd> FromFd for T { | |
61 | fn from_fd(fd: Fd) -> Self { | |
62 | unsafe { Self::from_raw_fd(fd.into_raw_fd()) } | |
63 | } | |
64 | } | |
cab6f1e6 WB |
65 | |
66 | /// This is totally unsafe. Only use this when you know what you're doing. | |
67 | #[derive(Debug, Clone)] | |
68 | #[repr(transparent)] | |
69 | pub struct AssertSendSync<T>(pub T); | |
70 | unsafe impl<T> Send for AssertSendSync<T> {} | |
71 | unsafe impl<T> Sync for AssertSendSync<T> {} |