1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use core::{alloc, convert};
use core::num::NonZeroUsize;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Layout(alloc::Layout);
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NonZeroLayout(Layout);
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct EmptyLayoutError;
impl Layout {
pub fn new<T>() -> Self {
Layout(alloc::Layout::new::<T>())
}
pub fn size(&self) -> usize {
self.0.size()
}
pub fn align(&self) -> usize {
self.0.align()
}
}
impl NonZeroLayout {
pub fn new<T>() -> Option<Self> {
Self::from_layout(Layout::new::<T>())
}
pub fn from_layout(layout: Layout) -> Option<Self> {
if layout.size() == 0 {
None
} else {
Some(NonZeroLayout(layout))
}
}
pub fn size(&self) -> NonZeroUsize {
NonZeroUsize::new(self.0.size()).unwrap()
}
pub fn align(&self) -> usize {
self.0.align()
}
}
impl From<Layout> for alloc::Layout {
fn from(layout: Layout) -> alloc::Layout {
layout.0
}
}
impl From<NonZeroLayout> for alloc::Layout {
fn from(layout: NonZeroLayout) -> alloc::Layout {
layout.0.into()
}
}
impl From<alloc::Layout> for Layout {
fn from(layout: alloc::Layout) -> Layout {
Layout(layout)
}
}
impl convert::TryFrom<Layout> for NonZeroLayout {
type Error = EmptyLayoutError;
fn try_from(layout: Layout) -> Result<Self, EmptyLayoutError> {
NonZeroLayout::from_layout(layout).ok_or(EmptyLayoutError)
}
}
impl convert::TryFrom<alloc::Layout> for NonZeroLayout {
type Error = EmptyLayoutError;
fn try_from(layout: alloc::Layout) -> Result<Self, EmptyLayoutError> {
NonZeroLayout::try_from(Layout::from(layout))
}
}