]> git.proxmox.com Git - pve-lxc-syscalld.git/blame - src/macros.rs
use OwnedFd for all remaining custom file descriptors
[pve-lxc-syscalld.git] / src / macros.rs
CommitLineData
636e29ad
WB
1// c_str!() from the byte-strings crate is implemented via a proc macro which seems a bit excessive
2macro_rules! c_str {
3 ($data:expr) => {{
d54e9e5a 4 #![allow(unused_unsafe)]
636e29ad
WB
5 let bytes = concat!($data, "\0");
6 unsafe { std::ffi::CStr::from_bytes_with_nul_unchecked(bytes.as_bytes()) }
7 }};
8}
9
f68bc5f1
WB
10macro_rules! file_descriptor_type {
11 ($type:ident) => {
12 #[repr(transparent)]
8a3c5add 13 pub struct $type(::std::os::unix::io::OwnedFd);
f68bc5f1
WB
14
15 file_descriptor_impl!($type);
16
0bad4328
WB
17 impl ::std::os::unix::io::FromRawFd for $type {
18 unsafe fn from_raw_fd(fd: ::std::os::unix::io::RawFd) -> Self {
8a3c5add 19 Self(unsafe { ::std::os::unix::io::FromRawFd::from_raw_fd(fd) })
f68bc5f1
WB
20 }
21 }
22 };
23}
24
25macro_rules! file_descriptor_impl {
26 ($type:ty) => {
0bad4328
WB
27 impl ::std::os::unix::io::AsFd for $type {
28 fn as_fd(&self) -> ::std::os::unix::io::BorrowedFd<'_> {
8a3c5add 29 ::std::os::unix::io::AsFd::as_fd(&self.0)
0bad4328
WB
30 }
31 }
32
33 impl ::std::os::unix::io::AsRawFd for $type {
34 fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd {
8a3c5add 35 ::std::os::unix::io::AsRawFd::as_raw_fd(&self.0)
f68bc5f1
WB
36 }
37 }
38
0bad4328 39 impl ::std::os::unix::io::IntoRawFd for $type {
8a3c5add
WB
40 fn into_raw_fd(self) -> ::std::os::unix::io::RawFd {
41 ::std::os::unix::io::IntoRawFd::into_raw_fd(self.0)
f68bc5f1
WB
42 }
43 }
44 };
45}
46
a18b03f3 47macro_rules! c_result {
f68bc5f1
WB
48 ($expr:expr) => {{
49 let res = $expr;
50 if res == -1 {
51 Err(::std::io::Error::last_os_error())
52 } else {
53 Ok::<_, ::std::io::Error>(res)
54 }
55 }};
56}
57
58macro_rules! c_try {
59 ($expr:expr) => {
a18b03f3 60 c_result!($expr)?
f68bc5f1
WB
61 };
62}
63
64macro_rules! io_format_err {
65 ($($msg:tt)*) => {
66 ::std::io::Error::new(::std::io::ErrorKind::Other, format!($($msg)*))
67 };
68}
69
70macro_rules! io_bail {
71 ($($msg:tt)*) => {
72 return Err(::std::io::Error::new(::std::io::ErrorKind::Other, format!($($msg)*)));
73 };
74}