1use core::{
2 alloc::{Layout, LayoutError},
3 fmt,
4 ops::Deref,
5};
6
7pub(crate) trait LayoutProps: Deref<Target = Layout> + Copy {
8 const ALIGN_IS_CONST: bool;
9 const SIZE_IS_CONST: bool;
10 const SIZE_IS_MULTIPLE_OF_ALIGN: bool;
11}
12
13#[derive(Clone, Copy)]
14pub(crate) struct SizedLayout(Layout);
15
16impl LayoutProps for SizedLayout {
17 const ALIGN_IS_CONST: bool = true;
18 const SIZE_IS_CONST: bool = true;
19 const SIZE_IS_MULTIPLE_OF_ALIGN: bool = true;
20}
21
22impl SizedLayout {
23 #[inline(always)]
24 pub(crate) const fn new<T>() -> Self {
25 Self(Layout::new::<T>())
26 }
27}
28
29impl Deref for SizedLayout {
30 type Target = Layout;
31
32 fn deref(&self) -> &Self::Target {
33 &self.0
34 }
35}
36
37#[derive(Clone, Copy)]
38pub(crate) struct ArrayLayout(Layout);
39
40impl LayoutProps for ArrayLayout {
41 const ALIGN_IS_CONST: bool = true;
42 const SIZE_IS_CONST: bool = false;
43 const SIZE_IS_MULTIPLE_OF_ALIGN: bool = true;
44}
45
46impl ArrayLayout {
47 #[inline(always)]
48 pub(crate) fn for_value<T>(value: &[T]) -> Self {
49 Self(Layout::for_value(value))
50 }
51
52 #[inline(always)]
53 pub(crate) fn array<T>(len: usize) -> Result<Self, LayoutError> {
54 Ok(Self(Layout::array::<T>(len)?))
55 }
56
57 #[inline(always)]
58 pub(crate) const fn from_layout(layout: Layout) -> Result<Self, ArrayLayoutError> {
59 if layout.size() % layout.align() == 0 {
60 Ok(ArrayLayout(layout))
61 } else {
62 Err(ArrayLayoutError)
63 }
64 }
65
66 #[inline(always)]
67 pub(crate) const fn from_size_align(size: usize, align: usize) -> Result<Self, ArrayLayoutError> {
68 match Layout::from_size_align(size, align) {
69 Ok(layout) => Self::from_layout(layout),
70 Err(_) => Err(ArrayLayoutError),
71 }
72 }
73}
74
75impl Deref for ArrayLayout {
76 type Target = Layout;
77
78 fn deref(&self) -> &Self::Target {
79 &self.0
80 }
81}
82
83#[derive(Clone, Copy)]
89pub(crate) struct CustomLayout(pub(crate) Layout);
90
91impl LayoutProps for CustomLayout {
92 const ALIGN_IS_CONST: bool = false;
93 const SIZE_IS_CONST: bool = false;
94 const SIZE_IS_MULTIPLE_OF_ALIGN: bool = false;
95}
96
97impl Deref for CustomLayout {
98 type Target = Layout;
99
100 fn deref(&self) -> &Self::Target {
101 &self.0
102 }
103}
104
105#[derive(Clone, Copy, PartialEq, Eq, Debug)]
106pub(crate) struct ArrayLayoutError;
107
108impl fmt::Display for ArrayLayoutError {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 f.write_str("invalid parameters to ArrayLayout constructor")
111 }
112}