rustix/
utils.rs

1//! Miscellaneous minor utilities.
2
3#![allow(dead_code)]
4#![allow(unused_macros)]
5
6use core::ffi::c_void;
7use core::mem::{align_of, size_of};
8use core::ptr::{null, null_mut, NonNull};
9
10/// Convert a `&T` into a `*const T` without using an `as`.
11#[inline]
12pub(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]
18pub(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]
24pub(crate) const fn option_as_ptr<T>(t: Option<&T>) -> *const T {
25    match t {
26        Some(t) => t,
27        None => null(),
28    }
29}
30
31/// Convert an `Option<&mut T>` into a possibly-null `*mut T`.
32#[inline]
33pub(crate) fn option_as_mut_ptr<T>(t: Option<&mut T>) -> *mut T {
34    match t {
35        Some(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.
43pub(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(value.cast())
51}
52
53/// Create an array value containing all default values, inferring the type.
54#[inline]
55pub(crate) fn default_array<T: Default + Copy, const N: usize>() -> [T; N] {
56    [T::default(); N]
57}
58
59/// Create a union value containing a default value in one of its arms.
60///
61/// The field names a union field which must have the same size as the union
62/// itself.
63macro_rules! default_union {
64    ($union:ident, $field:ident) => {{
65        let u = $union {
66            $field: Default::default(),
67        };
68
69        // Assert that the given field initializes the whole union.
70        #[cfg(test)]
71        unsafe {
72            let field_value = u.$field;
73            assert_eq!(
74                core::mem::size_of_val(&u),
75                core::mem::size_of_val(&field_value)
76            );
77            const_assert_eq!(memoffset::offset_of_union!($union, $field), 0);
78        }
79
80        u
81    }};
82}