]> git.proxmox.com Git - pve-lxc-syscalld.git/blame - src/tools.rs
bump version to 0.9.2-1
[pve-lxc-syscalld.git] / src / tools.rs
CommitLineData
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
6use 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)]
12pub struct Fd(pub RawFd);
13
14file_descriptor_impl!(Fd);
15
512f780a
WB
16impl FromRawFd for Fd {
17 unsafe fn from_raw_fd(fd: RawFd) -> Self {
18 Self(fd)
19 }
20}
21
9ebd1972 22impl 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
5bd0c562
WB
32impl AsRef<RawFd> for Fd {
33 #[inline]
34 fn as_ref(&self) -> &RawFd {
35 &self.0
36 }
37}
38
9cffeac4
WB
39/// Byte vector utilities.
40pub mod vec {
41 /// Create an uninitialized byte vector of a specific size.
42 ///
43 /// This is just a shortcut for:
44 /// ```no_run
45 /// # let len = 64usize;
46 /// let mut v = Vec::<u8>::with_capacity(len);
47 /// unsafe {
48 /// v.set_len(len);
49 /// }
50 /// ```
92eface0
WB
51 ///
52 /// # Safety
53 ///
54 /// This is generally safe to call, but the contents of the vector are undefined.
52f50bd4 55 #[inline]
9cffeac4
WB
56 pub unsafe fn uninitialized(len: usize) -> Vec<u8> {
57 let mut out = Vec::with_capacity(len);
58 out.set_len(len);
59 out
60 }
61}
571dbe03 62
512f780a
WB
63pub trait FromFd {
64 fn from_fd(fd: Fd) -> Self;
65}
66
67impl<T: FromRawFd> FromFd for T {
68 fn from_fd(fd: Fd) -> Self {
69 unsafe { Self::from_raw_fd(fd.into_raw_fd()) }
70 }
71}
cab6f1e6
WB
72
73/// This is totally unsafe. Only use this when you know what you're doing.
74#[derive(Debug, Clone)]
75#[repr(transparent)]
76pub struct AssertSendSync<T>(pub T);
77unsafe impl<T> Send for AssertSendSync<T> {}
78unsafe impl<T> Sync for AssertSendSync<T> {}