1#![allow(dead_code)]
2
3use core::ffi::c_void;
4use core::mem::{align_of, size_of};
5use core::ptr::{null, null_mut, NonNull};
6
7/// Convert a `&T` into a `*const T` without using an `as`.
8#[inline]
9pub(crate) const fn as_ptr<T>(t: &T) -> *const T {
10 t
11}
12
13/// Convert a `&mut T` into a `*mut T` without using an `as`.
14#[inline]
15pub(crate) fn as_mut_ptr<T>(t: &mut T) -> *mut T {
16 t
17}
18
19/// Convert an `Option<&T>` into a possibly-null `*const T`.
20#[inline]
21pub(crate) const fn optional_as_ptr<T>(t: Option<&T>) -> *const T {
22 match t {
23 Some(t: &T) => t,
24 None => null(),
25 }
26}
27
28/// Convert an `Option<&mut T>` into a possibly-null `*mut T`.
29#[inline]
30pub(crate) fn optional_as_mut_ptr<T>(t: Option<&mut T>) -> *mut T {
31 match t {
32 Some(t: &mut T) => t,
33 None => null_mut(),
34 }
35}
36
37/// Convert a `*mut c_void` to a `*mut T`, checking that it is not null,
38/// misaligned, or pointing to a region of memory that wraps around the address
39/// space.
40pub(crate) fn check_raw_pointer<T>(value: *mut c_void) -> Option<NonNull<T>> {
41 if (value as usize).checked_add(size_of::<T>()).is_none()
42 || (value as usize) % align_of::<T>() != 0
43 {
44 return None;
45 }
46
47 NonNull::new(ptr:value.cast())
48}
49