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