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
pub mod block;
pub mod chunks;
pub mod global;
use std::alloc::Layout;
pub struct Location<H> {
pub(crate) ptr: *mut u8,
pub(crate) header: H,
pub(crate) layout: Layout,
}
pub trait Region<H> {
type Pointers: Iterator<Item = *mut u8>;
fn allocate(&mut self, layout: Layout, header: H) -> Result<*mut u8, H>;
fn deallocate(&mut self, ptr: *mut u8) -> Option<H>;
fn has_allocated(&self, ptr: *mut u8) -> bool;
fn allocations(&self) -> Self::Pointers;
fn count(&self) -> usize;
fn deallocate_all(&mut self) -> DeallocateAll<'_, H, Self>
where
Self: Sized,
{
DeallocateAll {
iter: self.allocations(),
region: self,
}
}
}
pub struct DeallocateAll<'a, H, R: Region<H>> {
region: &'a mut R,
iter: R::Pointers,
}
impl<'a, H, R: Region<H>> Iterator for DeallocateAll<'a, H, R> {
type Item = (*mut u8, H);
fn next(&mut self) -> Option<Self::Item> {
let ptr = self.iter.next()?;
Some((ptr, self.region.deallocate(ptr).unwrap()))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a, H, R> ExactSizeIterator for DeallocateAll<'a, H, R>
where
R: Region<H>,
R::Pointers: ExactSizeIterator,
{
fn len(&self) -> usize {
self.iter.len()
}
}
impl<'a, H, R> std::iter::FusedIterator for DeallocateAll<'a, H, R>
where
R: Region<H>,
R::Pointers: std::iter::FusedIterator,
{
}
impl<'a, H, R> std::iter::DoubleEndedIterator for DeallocateAll<'a, H, R>
where
R: Region<H>,
R::Pointers: std::iter::DoubleEndedIterator,
{
fn next_back(&mut self) -> Option<Self::Item> {
let ptr = self.iter.next_back()?;
Some((ptr, self.region.deallocate(ptr).unwrap()))
}
}
#[cfg(test)]
#[test]
fn deallocate_all() {
let mut chunks = chunks::Chunks::new(4);
let vec: Vec<*mut u8> = (0..100)
.map(|_| chunks.allocate(Layout::new::<u8>(), ()).unwrap())
.collect();
for _ in chunks.deallocate_all() {}
for ptr in vec {
assert_eq!(chunks.deallocate(ptr), None);
}
}