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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use core::{alloc::Layout, cmp, fmt, marker::PhantomData, ops, ptr};
use alloc_many::Alloc;
use crate::unique::Unique;
pub struct Box<A, T>
where
A: Alloc,
T: ?Sized,
{
_allocator: PhantomData<A>,
ptr: Unique<T>,
}
impl<A, T> Box<A, T>
where
A: Alloc,
{
pub fn new(value: T) -> Self {
let layout = Layout::new::<T>();
unsafe {
Unique::new(A::alloc(layout) as *mut T)
.map(|ptr| {
ptr.as_ptr().write(value);
Box {
_allocator: PhantomData,
ptr,
}
})
.unwrap_or_else(|| crate::alloc_many_oom(layout))
}
}
}
impl<A, T> ops::Deref for Box<A, T>
where
T: ?Sized,
A: Alloc,
{
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
}
impl<A, T> ops::DerefMut for Box<A, T>
where
T: ?Sized,
A: Alloc,
{
fn deref_mut(&mut self) -> &mut T {
unsafe { self.ptr.as_mut() }
}
}
impl<A, T> Drop for Box<A, T>
where
A: Alloc,
T: ?Sized,
{
fn drop(&mut self) {
unsafe {
let layout = Layout::for_value(self.ptr.as_ref());
let ptr = self.ptr.as_ptr();
ptr::drop_in_place(ptr);
A::dealloc(ptr as *mut u8, layout)
}
}
}
impl<A, T> fmt::Debug for Box<A, T>
where
T: ?Sized + fmt::Debug,
A: Alloc,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
<T as fmt::Debug>::fmt(self, f)
}
}
impl<A, T> fmt::Display for Box<A, T>
where
T: ?Sized + fmt::Display,
A: Alloc,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
<T as fmt::Display>::fmt(self, f)
}
}
impl<A, T> Eq for Box<A, T>
where
T: ?Sized + Eq,
A: Alloc,
{
}
impl<A, B, T> PartialEq<Box<B, T>> for Box<A, T>
where
T: ?Sized + PartialEq,
A: Alloc,
B: Alloc,
{
fn eq(&self, other: &Box<B, T>) -> bool {
<T as PartialEq>::eq(self, other)
}
}
impl<A, B, T> PartialOrd<Box<B, T>> for Box<A, T>
where
T: ?Sized + PartialOrd,
A: Alloc,
B: Alloc,
{
fn partial_cmp(&self, other: &Box<B, T>) -> Option<cmp::Ordering> {
<T as PartialOrd>::partial_cmp(self, other)
}
}