ref_cast/
layout.rs

1use core::mem;
2
3#[doc(hidden)]
4pub struct Layout<T: ?Sized>(T);
5
6#[doc(hidden)]
7pub trait LayoutUnsized<T: ?Sized> {
8    const SIZE: usize = usize::MAX;
9    const ALIGN: usize = usize::MAX;
10}
11
12impl<T: ?Sized> LayoutUnsized<T> for Layout<T> {}
13
14impl<T> Layout<T> {
15    pub const SIZE: usize = mem::size_of::<T>();
16    pub const ALIGN: usize = mem::align_of::<T>();
17}
18
19#[doc(hidden)]
20#[inline]
21pub fn assert_layout<Outer: ?Sized, Inner: ?Sized>(
22    name: &'static str,
23    outer_size: usize,
24    inner_size: usize,
25    outer_align: usize,
26    inner_align: usize,
27) {
28    if outer_size != inner_size {
29        #[cfg(no_intrinsic_type_name)]
30        panic!(
31            "unexpected size in cast to {}: {} != {}",
32            name, outer_size, inner_size,
33        );
34        #[cfg(not(no_intrinsic_type_name))]
35        panic!(
36            "unexpected size in cast from {} to {}: {} != {}",
37            core::any::type_name::<Inner>(),
38            core::any::type_name::<Outer>(),
39            inner_size,
40            outer_size,
41        );
42    }
43    if outer_align != inner_align {
44        #[cfg(no_intrinsic_type_name)]
45        panic!(
46            "unexpected alignment in cast to {}: {} != {}",
47            name, outer_align, inner_align,
48        );
49        #[cfg(not(no_intrinsic_type_name))]
50        panic!(
51            "unexpected alignment in cast from {} to {}: {} != {}",
52            core::any::type_name::<Inner>(),
53            core::any::type_name::<Outer>(),
54            inner_align,
55            outer_align,
56        );
57    }
58    #[cfg(not(no_intrinsic_type_name))]
59    let _ = name;
60}