]> git.proxmox.com Git - pve-lxc-syscalld.git/blame - src/tools.rs
replace custom Fd with std OwnedFd
[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
caeb9675 6use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
2c58f785
WB
7
8pub fn set_fd_nonblocking<T: AsRawFd + ?Sized>(fd: &T, on: bool) -> nix::Result<libc::c_int> {
9 use nix::fcntl;
10 let fd = fd.as_raw_fd();
11 let mut flags = fcntl::OFlag::from_bits(fcntl::fcntl(fd, fcntl::FcntlArg::F_GETFL)?).unwrap();
12 flags.set(fcntl::OFlag::O_NONBLOCK, on);
13 fcntl::fcntl(fd, fcntl::FcntlArg::F_SETFL(flags))
14}
9cffeac4 15
9cffeac4
WB
16/// Byte vector utilities.
17pub mod vec {
18 /// Create an uninitialized byte vector of a specific size.
19 ///
20 /// This is just a shortcut for:
21 /// ```no_run
22 /// # let len = 64usize;
23 /// let mut v = Vec::<u8>::with_capacity(len);
24 /// unsafe {
25 /// v.set_len(len);
26 /// }
27 /// ```
92eface0
WB
28 ///
29 /// # Safety
30 ///
31 /// This is generally safe to call, but the contents of the vector are undefined.
52f50bd4 32 #[inline]
9cffeac4 33 pub unsafe fn uninitialized(len: usize) -> Vec<u8> {
4032c669
WB
34 unsafe {
35 let data = std::alloc::alloc(std::alloc::Layout::array::<u8>(len).unwrap());
36 Vec::from_raw_parts(data as *mut u8, len, len)
37 }
9cffeac4
WB
38 }
39}
571dbe03 40
512f780a 41pub trait FromFd {
2c58f785 42 fn from_fd<T: IntoRawFd>(fd: T) -> Self;
512f780a
WB
43}
44
45impl<T: FromRawFd> FromFd for T {
2c58f785 46 fn from_fd<F: IntoRawFd>(fd: F) -> Self {
512f780a
WB
47 unsafe { Self::from_raw_fd(fd.into_raw_fd()) }
48 }
49}
cab6f1e6
WB
50
51/// This is totally unsafe. Only use this when you know what you're doing.
52#[derive(Debug, Clone)]
53#[repr(transparent)]
54pub struct AssertSendSync<T>(pub T);
55unsafe impl<T> Send for AssertSendSync<T> {}
56unsafe impl<T> Sync for AssertSendSync<T> {}