osom_lib_reprc/
traits.rs

1use core::{
2    marker::PhantomData,
3    ptr::NonNull,
4    sync::atomic::{
5        AtomicBool, AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicIsize, AtomicPtr, AtomicU8, AtomicU16, AtomicU32,
6        AtomicU64, AtomicUsize,
7    },
8};
9
10/// Ensures that the type implementing it is `#[repr(C)]`.
11/// This cannot be guaranteed in general, and therefore we
12/// rely on macros to achieve that. This is a marker trait.
13///
14/// # Safety
15///
16/// This is an inherently unsafe trait. Any type implementing it
17/// has to have `#[repr(C)]` set recursively.
18pub unsafe trait ReprC {
19    /// This field is used for const checks only.
20    const CHECK: ();
21}
22
23macro_rules! impl_reprc {
24    ( $t: ty ) => {
25        unsafe impl ReprC for $t {
26            const CHECK: () = ();
27        }
28    };
29
30    ( $t: ty, $($ta: ty),* ) => {
31        impl_reprc!($t);
32        impl_reprc!($($ta),*);
33    }
34}
35
36macro_rules! impl_generic_reprc {
37    ( $t: ty ) => {
38        unsafe impl<T: ReprC> ReprC for $t {
39            const CHECK: () = ();
40        }
41    };
42
43    ( $t: ty, $($ta: ty),* ) => {
44        impl_generic_reprc!($t);
45        impl_generic_reprc!($($ta),*);
46    }
47}
48
49impl_reprc!(
50    i8,
51    u8,
52    i16,
53    u16,
54    i32,
55    u32,
56    i64,
57    u64,
58    i128,
59    u128,
60    f32,
61    f64,
62    (),
63    bool,
64    isize,
65    usize,
66    AtomicBool,
67    AtomicI8,
68    AtomicU8,
69    AtomicI16,
70    AtomicU16,
71    AtomicI32,
72    AtomicU32,
73    AtomicI64,
74    AtomicU64,
75    AtomicIsize,
76    AtomicUsize
77);
78
79impl_generic_reprc!(AtomicPtr<T>, *const T, *mut T, &T, &mut T, NonNull<T>);
80
81unsafe impl<T: ReprC, const N: usize> ReprC for [T; N] {
82    const CHECK: () = ();
83}
84
85// PhantomData is a special case, that works with any T, since its size is 0
86// anyway.
87unsafe impl<T> ReprC for PhantomData<T> {
88    const CHECK: () = {
89        assert!(size_of::<PhantomData<T>>() == 0);
90    };
91}