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
use bitflags::bitflags;
use core::mem::size_of;
use core::ptr::NonNull;
bitflags! {
pub struct RegionFlags: u16 {
const IN_USE = 1;
}
}
#[repr(C)]
#[derive(Debug)]
pub struct Region {
pub size: usize,
pub data: usize,
pub padding_start: usize,
pub padding_end: usize,
pub flags: RegionFlags,
pub prev: usize,
pub next: usize,
}
impl Region {
pub fn new(addr: usize, size: usize) -> Region {
assert!(size >= Self::min_size());
Region {
size: size - size_of::<Self>(),
data: addr + size_of::<Self>(),
padding_start: 0,
padding_end: 0,
flags: RegionFlags::empty(),
prev: 0,
next: 0,
}
}
pub fn new_with_padding(
addr: usize,
size: usize,
padding_start: usize,
padding_end: usize,
) -> Region {
let mut region = Region::new(addr, size);
region.padding_start = padding_start;
region.padding_end = padding_end;
region
}
pub fn min_size() -> usize {
size_of::<Self>() + (size_of::<usize>() * 4)
}
pub fn get_used(&self) -> bool {
self.flags.contains(RegionFlags::IN_USE)
}
pub fn set_used(&mut self, used: bool) {
self.flags.set(RegionFlags::IN_USE, used);
}
pub fn size(&self) -> usize {
self.padding_start
.wrapping_add(self.size)
.wrapping_add(self.padding_end)
}
pub unsafe fn header_ptr(&self) -> Option<NonNull<u8>> {
Some(NonNull::new_unchecked(
(self.data - size_of::<Self>()) as *mut u8,
))
}
pub unsafe fn data_ptr(&self) -> Option<NonNull<u8>> {
if self.data == 0 {
None
} else {
Some(NonNull::new_unchecked(
(self.data + self.padding_start) as *mut u8,
))
}
}
}