]>
Commit | Line | Data |
---|---|---|
636e29ad WB |
1 | // c_str!() from the byte-strings crate is implemented via a proc macro which seems a bit excessive |
2 | macro_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 |
10 | macro_rules! file_descriptor_type { |
11 | ($type:ident) => { | |
12 | #[repr(transparent)] | |
0bad4328 | 13 | pub struct $type(::std::os::unix::io::RawFd); |
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 { | |
f68bc5f1 WB |
19 | Self(fd) |
20 | } | |
21 | } | |
22 | }; | |
23 | } | |
24 | ||
25 | macro_rules! file_descriptor_impl { | |
26 | ($type:ty) => { | |
27 | impl Drop for $type { | |
28 | fn drop(&mut self) { | |
29 | if self.0 >= 0 { | |
30 | unsafe { | |
31 | libc::close(self.0); | |
32 | } | |
33 | } | |
34 | } | |
35 | } | |
36 | ||
0bad4328 WB |
37 | impl ::std::os::unix::io::AsFd for $type { |
38 | fn as_fd(&self) -> ::std::os::unix::io::BorrowedFd<'_> { | |
39 | unsafe { ::std::os::unix::io::BorrowedFd::borrow_raw(self.0) } | |
40 | } | |
41 | } | |
42 | ||
43 | impl ::std::os::unix::io::AsRawFd for $type { | |
44 | fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd { | |
f68bc5f1 WB |
45 | self.0 |
46 | } | |
47 | } | |
48 | ||
0bad4328 WB |
49 | impl ::std::os::unix::io::IntoRawFd for $type { |
50 | fn into_raw_fd(mut self) -> ::std::os::unix::io::RawFd { | |
f68bc5f1 WB |
51 | let fd = self.0; |
52 | self.0 = -libc::EBADF; | |
53 | fd | |
54 | } | |
55 | } | |
56 | }; | |
57 | } | |
58 | ||
a18b03f3 | 59 | macro_rules! c_result { |
f68bc5f1 WB |
60 | ($expr:expr) => {{ |
61 | let res = $expr; | |
62 | if res == -1 { | |
63 | Err(::std::io::Error::last_os_error()) | |
64 | } else { | |
65 | Ok::<_, ::std::io::Error>(res) | |
66 | } | |
67 | }}; | |
68 | } | |
69 | ||
70 | macro_rules! c_try { | |
71 | ($expr:expr) => { | |
a18b03f3 | 72 | c_result!($expr)? |
f68bc5f1 WB |
73 | }; |
74 | } | |
75 | ||
76 | macro_rules! io_format_err { | |
77 | ($($msg:tt)*) => { | |
78 | ::std::io::Error::new(::std::io::ErrorKind::Other, format!($($msg)*)) | |
79 | }; | |
80 | } | |
81 | ||
82 | macro_rules! io_bail { | |
83 | ($($msg:tt)*) => { | |
84 | return Err(::std::io::Error::new(::std::io::ErrorKind::Other, format!($($msg)*))); | |
85 | }; | |
86 | } |