zx/macros.rs
1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Implements the HandleBased traits for a Handle newtype struct
6macro_rules! impl_handle_based {
7 ($type_name:path) => {
8 impl AsHandleRef for $type_name {
9 fn as_handle_ref(&self) -> HandleRef<'_> {
10 self.0.as_handle_ref()
11 }
12 }
13
14 impl From<NullableHandle> for $type_name {
15 fn from(handle: NullableHandle) -> Self {
16 $type_name(handle)
17 }
18 }
19
20 impl From<$type_name> for NullableHandle {
21 fn from(x: $type_name) -> NullableHandle {
22 x.0
23 }
24 }
25
26 impl HandleBased for $type_name {}
27
28 impl $type_name {
29 delegated_concrete_handle_based_impls!(Self);
30 }
31 };
32}
33
34macro_rules! delegated_concrete_handle_based_impls {
35 ($ctor:expr) => {
36 /// Return the raw handle's integer value without closing it when `self` is dropped.
37 pub fn into_raw(self) -> $crate::sys::zx_handle_t {
38 self.0.into_raw()
39 }
40
41 // TODO(https://fxbug.dev/384752843) only generate on types that can be duped
42 /// Wraps the
43 /// [`zx_handle_duplicate`](https://fuchsia.dev/fuchsia-src/reference/syscalls/handle_duplicate)
44 /// syscall.
45 pub fn duplicate(&self, rights: $crate::Rights) -> Result<Self, $crate::Status> {
46 self.0.duplicate(rights).map($ctor)
47 }
48
49 /// Wraps the
50 /// [`zx_handle_replace`](https://fuchsia.dev/fuchsia-src/reference/syscalls/handle_replace)
51 /// syscall.
52 pub fn replace(self, rights: $crate::Rights) -> Result<Self, $crate::Status> {
53 self.0.replace(rights).map($ctor)
54 }
55
56 /// Wraps the
57 /// [`zx_object_signal`](https://fuchsia.dev/fuchsia-src/reference/syscalls/object_signal)
58 /// syscall.
59 pub fn signal(
60 &self,
61 clear_mask: $crate::Signals,
62 set_mask: $crate::Signals,
63 ) -> Result<(), $crate::Status> {
64 self.0.signal(clear_mask, set_mask)
65 }
66
67 /// Wraps the
68 /// [`zx_object_wait_one`](https://fuchsia.dev/fuchsia-src/reference/syscalls/object_wait_one)
69 /// syscall.
70 pub fn wait_one(
71 &self,
72 signals: $crate::Signals,
73 deadline: $crate::MonotonicInstant,
74 ) -> $crate::WaitResult {
75 self.0.wait_one(signals, deadline)
76 }
77
78 /// Wraps the
79 /// [`zx_object_wait_async`](https://fuchsia.dev/fuchsia-src/reference/syscalls/object_wait_async)
80 /// syscall.
81 pub fn wait_async(
82 &self,
83 port: &$crate::Port,
84 key: u64,
85 signals: $crate::Signals,
86 options: $crate::WaitAsyncOpts,
87 ) -> Result<(), $crate::Status> {
88 self.0.wait_async(port, key, signals, options)
89 }
90
91 /// Wraps a call to the
92 /// [`zx_object_get_property`](https://fuchsia.dev/fuchsia-src/reference/syscalls/object_get_property)
93 /// syscall for the `ZX_PROP_NAME` property.
94 pub fn get_name(&self) -> Result<$crate::Name, $crate::Status> {
95 self.0.get_name()
96 }
97
98 /// Wraps a call to the
99 /// [`zx_object_set_property`](https://fuchsia.dev/fuchsia-src/reference/syscalls/object_set_property)
100 /// syscall for the `ZX_PROP_NAME` property.
101 pub fn set_name(&self, name: &$crate::Name) -> Result<(), $crate::Status> {
102 self.0.set_name(name)
103 }
104
105 /// Wraps the
106 /// [`zx_object_get_info`](https://fuchsia.dev/fuchsia-src/reference/syscalls/object_get_info)
107 /// syscall for the `ZX_INFO_HANDLE_BASIC` topic.
108 pub fn basic_info(&self) -> Result<$crate::HandleBasicInfo, $crate::Status> {
109 self.0.basic_info()
110 }
111
112 /// Wraps the
113 /// [`zx_object_get_info`](https://fuchsia.dev/fuchsia-src/reference/syscalls/object_get_info)
114 /// syscall for the `ZX_INFO_HANDLE_COUNT` topic.
115 pub fn count_info(&self) -> Result<$crate::HandleCountInfo, $crate::Status> {
116 self.0.count_info()
117 }
118
119 /// Returns the [Koid] for the object referred to by this handle.
120 pub fn koid(&self) -> Result<$crate::Koid, $crate::Status> {
121 self.0.koid()
122 }
123 };
124}
125
126/// Convenience macro for creating get/set property functions on an object.
127///
128/// This is for use when the underlying property type is a simple raw type.
129/// It creates an empty 'tag' struct to implement the relevant PropertyQuery*
130/// traits against. One, or both, of a getter and setter may be defined
131/// depending upon what the property supports. Example usage is
132/// unsafe_handle_propertyes!(ObjectType[get_foo_prop,set_foo_prop:FooPropTag,FOO,u32;]);
133/// unsafe_handle_properties!(object: Foo,
134/// props: [
135/// {query_ty: FOO_BAR, tag: FooBarTag, prop_ty: usize, get:get_bar},
136/// {query_ty: FOO_BAX, tag: FooBazTag, prop_ty: u32, set:set_baz},
137/// ]
138/// );
139/// And will create
140/// Foo::get_bar(&self) -> Result<usize, Status>
141/// Foo::set_baz(&self, val: &u32) -> Result<(), Status>
142/// Using Property::FOO as the underlying property.
143///
144/// # Safety
145///
146/// This macro will implement unsafe traits on your behalf and any combination
147/// of query_ty and prop_ty must respect the Safety requirements detailed on the
148/// PropertyQuery trait.
149macro_rules! unsafe_handle_properties {
150 (
151 object: $object_ty:ty,
152 props: [$( {
153 query_ty: $query_ty:ident,
154 tag: $query_tag:ident,
155 prop_ty: $prop_ty:ty
156 $(,get: $get:ident)*
157 $(,set: $set:ident)*
158 $(,)*
159 }),*$(,)*]
160 ) => {
161 $(
162 struct $query_tag {}
163 unsafe impl PropertyQuery for $query_tag {
164 const PROPERTY: Property = Property::$query_ty;
165 type PropTy = $prop_ty;
166 }
167
168 $(
169 impl $object_ty {
170 pub fn $get(&self) -> Result<$prop_ty, Status> {
171 self.0.get_property::<$query_tag>()
172 }
173 }
174 )*
175
176 $(
177 impl $object_ty {
178 pub fn $set(&self, val: &$prop_ty) -> Result<(), Status> {
179 self.0.set_property::<$query_tag>(val)
180 }
181 }
182 )*
183 )*
184 }
185}
186
187// Creates associated constants of TypeName of the form
188// `pub const NAME: TypeName = TypeName(path::to::value);`
189// and provides a private `assoc_const_name` method and a `Debug` implementation
190// for the type based on `$name`.
191// If multiple names match, the first will be used in `name` and `Debug`.
192#[macro_export]
193macro_rules! assoc_values {
194 ($typename:ident, [$($(#[$attr:meta])* $name:ident = $value:path;)*]) => {
195 #[allow(non_upper_case_globals)]
196 impl $typename {
197 $(
198 $(#[$attr])*
199 pub const $name: $typename = $typename($value);
200 )*
201
202 fn assoc_const_name(&self) -> Option<&'static str> {
203 match self.0 {
204 $(
205 $(#[$attr])*
206 $value => Some(stringify!($name)),
207 )*
208 _ => None,
209 }
210 }
211 }
212
213 impl ::std::fmt::Debug for $typename {
214 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
215 f.write_str(concat!(stringify!($typename), "("))?;
216 match self.assoc_const_name() {
217 Some(name) => f.write_str(&name)?,
218 None => ::std::fmt::Debug::fmt(&self.0, f)?,
219 }
220 f.write_str(")")
221 }
222 }
223 }
224}
225
226/// Declare a struct that needs to be statically aligned with another, equivalent struct. The syntax
227/// is the following:
228/// rust```
229/// static_assert_align! (
230/// #[derive(Trait1, Trait2)]
231/// <other_aligned_struct> pub struct MyStruct {
232/// field_1 <equivalent_field1_on_other_struct>: bool,
233/// field_2 <equivalent_field2_on_other_struct>: u32,
234/// special_field_3: [u8; 10], // This field will be ignored when comparing alignment.
235/// }
236/// );
237/// ```
238macro_rules! static_assert_align {
239 (
240 $(#[$attrs:meta])* <$equivalent:ty> $vis:vis struct $struct_name:ident {
241 $($field_vis:vis $field_ident:ident $(<$field_eq:ident>)?: $field_type:ty,)*
242 }
243 ) => {
244 $(#[$attrs])* $vis struct $struct_name {
245 $($field_vis $field_ident: $field_type,)*
246 }
247
248 static_assertions::assert_eq_size!($struct_name, $equivalent);
249 $(_static_assert_one_field!($struct_name, $field_ident, $equivalent $(, $field_eq)?);)*
250 }
251}
252
253/// Internal macro used by [static_assert_align].
254macro_rules! _static_assert_one_field {
255 ($struct_1:ty, $field_1:ident, $struct_2:ty) => {};
256 ($struct_1:ty, $field_1:ident, $struct_2:ty, $field_2:ident) => {
257 static_assertions::const_assert_eq!(
258 std::mem::offset_of!($struct_1, $field_1),
259 std::mem::offset_of!($struct_2, $field_2)
260 );
261 };
262}