| 1 | //! Miscellaneous minor utilities. |
| 2 | |
| 3 | #![allow (dead_code)] |
| 4 | #![allow (unused_macros)] |
| 5 | |
| 6 | use core::ffi::c_void; |
| 7 | use core::mem::{align_of, size_of}; |
| 8 | use core::ptr::{null, null_mut, NonNull}; |
| 9 | |
| 10 | /// Convert a `&T` into a `*const T` without using an `as`. |
| 11 | #[inline ] |
| 12 | pub(crate) const fn as_ptr<T>(t: &T) -> *const T { |
| 13 | t |
| 14 | } |
| 15 | |
| 16 | /// Convert a `&mut T` into a `*mut T` without using an `as`. |
| 17 | #[inline ] |
| 18 | pub(crate) fn as_mut_ptr<T>(t: &mut T) -> *mut T { |
| 19 | t |
| 20 | } |
| 21 | |
| 22 | /// Convert an `Option<&T>` into a possibly-null `*const T`. |
| 23 | #[inline ] |
| 24 | pub(crate) const fn option_as_ptr<T>(t: Option<&T>) -> *const T { |
| 25 | match t { |
| 26 | Some(t: &T) => t, |
| 27 | None => null(), |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /// Convert an `Option<&mut T>` into a possibly-null `*mut T`. |
| 32 | #[inline ] |
| 33 | pub(crate) fn option_as_mut_ptr<T>(t: Option<&mut T>) -> *mut T { |
| 34 | match t { |
| 35 | Some(t: &mut T) => t, |
| 36 | None => null_mut(), |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | /// Convert a `*mut c_void` to a `*mut T`, checking that it is not null, |
| 41 | /// misaligned, or pointing to a region of memory that wraps around the address |
| 42 | /// space. |
| 43 | pub(crate) fn check_raw_pointer<T>(value: *mut c_void) -> Option<NonNull<T>> { |
| 44 | if (value as usize).checked_add(size_of::<T>()).is_none() |
| 45 | || (value as usize) % align_of::<T>() != 0 |
| 46 | { |
| 47 | return None; |
| 48 | } |
| 49 | |
| 50 | NonNull::new(ptr:value.cast()) |
| 51 | } |
| 52 | |
| 53 | /// Create a union value containing a default value in one of its arms. |
| 54 | /// |
| 55 | /// The field names a union field which must have the same size as the union |
| 56 | /// itself. |
| 57 | macro_rules! default_union { |
| 58 | ($union:ident, $field:ident) => {{ |
| 59 | let u = $union { |
| 60 | $field: Default::default(), |
| 61 | }; |
| 62 | |
| 63 | // Assert that the given field initializes the whole union. |
| 64 | #[cfg(test)] |
| 65 | unsafe { |
| 66 | let field_value = u.$field; |
| 67 | assert_eq!( |
| 68 | core::mem::size_of_val(&u), |
| 69 | core::mem::size_of_val(&field_value) |
| 70 | ); |
| 71 | const_assert_eq!(memoffset::offset_of_union!($union, $field), 0); |
| 72 | } |
| 73 | |
| 74 | u |
| 75 | }}; |
| 76 | } |
| 77 | |