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
//! Data structures representing a memory region
use bitflags::bitflags;
use core::mem::size_of;
use core::ptr::NonNull;
bitflags! {
/// Flags for a given memory region
pub struct RegionFlags: u16 {
/// Signifies that the memory region is in use
const IN_USE = 1;
}
}
#[repr(C)]
#[derive(Debug)]
/// Header of a memory region.
pub struct Region {
/// Available size of the memory region (excluding the size of the header).
pub size: usize,
/// Starting address of this memory region's data
pub data: usize,
/// Number of bytes of padding to place at the start of the region
pub padding_start: usize,
/// Number of bytes of padding to place at the end of the region
pub padding_end: usize,
/// Flags for this memory region
pub flags: RegionFlags,
/// Address of the header of the memory regoin preceding this one
pub prev: usize,
/// Address of the header of the memory region following this one
pub next: usize,
}
impl Region {
/// Creates a new Region with the given `addr` and `size`.
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,
}
}
/// Creates a new Region with the given `addr` and `size`, and also sets
/// the start and end padding of the region.
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
}
/// The minimum size of a memory region.
pub fn min_size() -> usize {
size_of::<Self>() + (size_of::<usize>() * 2)
}
/// Returns whether or not this memory region is in use
pub fn get_used(&self) -> bool {
self.flags.contains(RegionFlags::IN_USE)
}
/// Sets the in use flag of this memory region to the value given in
/// `used`.
pub fn set_used(&mut self, used: bool) {
self.flags.set(RegionFlags::IN_USE, used);
}
/// Returns the total size, including padding, of this memory region
pub fn size(&self) -> usize {
self.padding_start
.wrapping_add(self.size)
.wrapping_add(self.padding_end)
}
/// Returns a raw pointer to this memory region's header
pub unsafe fn header_ptr(&self) -> Option<NonNull<u8>> {
Some(NonNull::new_unchecked(
(self.data - size_of::<Self>()) as *mut u8,
))
}
/// Returns a raw pointer to the data of this memory region
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,
))
}
}
}