-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathrange_alloc.rs
More file actions
102 lines (83 loc) · 2.63 KB
/
Copy pathrange_alloc.rs
File metadata and controls
102 lines (83 loc) · 2.63 KB
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
use bitvec::prelude::*;
pub type Range = std::ops::Range<u32>;
/// An allocator over a fixed address space.
///
/// Used to allocate sectors within region files.
pub struct RangeAllocator {
sectors: BitVec,
}
impl RangeAllocator {
pub fn new(size: u32) -> Self {
let sectors = bitvec![usize, Lsb0; 0; size as usize];
Self { sectors }
}
pub fn size(&self) -> u32 {
self.sectors.len() as u32
}
/// Resizes the allocator.
pub fn grow_to(&mut self, new_size: u32) {
assert!(new_size >= self.size(), "cannot shrink a range allocator");
let excess = new_size - self.size();
let zeros = bitvec![usize, Lsb0; 0; excess as usize];
self.sectors.extend_from_bitslice(&zeros);
assert_eq!(self.size(), new_size);
}
/// Allocates a new range.
pub fn allocate(&mut self, size: u32) -> Option<Range> {
let mut slice = &mut self.sectors[..];
let mut offset = 0;
while let Some(index) = slice.first_zero() {
if index + size as usize > slice.len() {
return None;
}
// Check if there is enough space in this free block
for i in index..index + size as usize {
if slice[i] {
slice = &mut slice[i..];
offset += i;
continue;
}
}
// Mark sectors as used, then return the new range.
for i in index..index + size as usize {
slice.set(i, true);
}
return Some(Range {
start: offset as u32 + index as u32,
end: offset as u32 + index as u32 + size,
});
}
None
}
/// Deallocates a range.
pub fn deallocate(&mut self, range: Range) {
for i in range {
assert!(self.sectors[i as usize]);
self.sectors.set(i as usize, false);
}
}
/// Marks the given block as used.
pub fn mark_used(&mut self, range: Range) {
for i in range {
self.sectors.set(i as usize, true);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alloc_consecutive() {
let mut alloc = RangeAllocator::new(101);
for i in 0..10 {
let block = alloc.allocate(10).unwrap();
assert_eq!(block.start, i * 10);
assert_eq!(block.end, i * 10 + 10);
}
assert!(alloc.allocate(10).is_none());
alloc.deallocate(90..100);
alloc.allocate(10).unwrap();
assert!(alloc.allocate(10).is_none());
alloc.allocate(1).unwrap();
}
}