]> git.proxmox.com Git - pve-lxc-syscalld.git/blob - src/tools.rs
1ae193ad08c0209d09d961549f47d4be68fb2d0b
[pve-lxc-syscalld.git] / src / tools.rs
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
6 use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
7
8 pub use io_uring::iovec::{IoVec, IoVecMut};
9
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
18 impl FromRawFd for Fd {
19 unsafe fn from_raw_fd(fd: RawFd) -> Self {
20 Self(fd)
21 }
22 }
23
24 /// Byte vector utilities.
25 pub mod vec {
26 /// Create an uninitialized byte vector of a specific size.
27 ///
28 /// This is just a shortcut for:
29 /// ```no_run
30 /// # let len = 64usize;
31 /// let mut v = Vec::<u8>::with_capacity(len);
32 /// unsafe {
33 /// v.set_len(len);
34 /// }
35 /// ```
36 ///
37 /// # Safety
38 ///
39 /// This is generally safe to call, but the contents of the vector are undefined.
40 #[inline]
41 pub unsafe fn uninitialized(len: usize) -> Vec<u8> {
42 let mut out = Vec::with_capacity(len);
43 out.set_len(len);
44 out
45 }
46 }
47
48 pub trait FromFd {
49 fn from_fd(fd: Fd) -> Self;
50 }
51
52 impl<T: FromRawFd> FromFd for T {
53 fn from_fd(fd: Fd) -> Self {
54 unsafe { Self::from_raw_fd(fd.into_raw_fd()) }
55 }
56 }