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 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.
57macro_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}