sel4_abstract_allocator/
by_range.rs
1use alloc::collections::BTreeMap;
8use core::alloc::Layout;
9use core::ops::Range;
10
11use crate::{AbstractAllocator, AbstractAllocatorAllocation};
12
13pub struct ByRange<A: AbstractAllocator> {
14 inner: A,
15 allocations: BTreeMap<RangeKey<usize>, A::Allocation>,
16}
17
18impl<A: AbstractAllocator> ByRange<A> {
19 pub const fn new(inner: A) -> Self {
20 Self {
21 inner,
22 allocations: BTreeMap::new(),
23 }
24 }
25
26 pub fn allocate(&mut self, layout: Layout) -> Result<Range<usize>, A::AllocationError> {
27 let allocation = self.inner.allocate(layout)?;
28 let range = allocation.range();
29 self.allocations.insert(range.clone().into(), allocation);
30 Ok(range)
31 }
32
33 pub fn deallocate(&mut self, range: Range<usize>) {
34 let allocation = self.allocations.remove(&range.into()).unwrap();
35 self.inner.deallocate(allocation)
36 }
37}
38
39#[derive(Eq, PartialEq, Ord, PartialOrd)]
40struct RangeKey<T> {
41 start: T,
42 end: T,
43}
44
45impl<T> From<Range<T>> for RangeKey<T> {
46 fn from(range: Range<T>) -> Self {
47 Self {
48 start: range.start,
49 end: range.end,
50 }
51 }
52}
53
54impl<T> From<RangeKey<T>> for Range<T> {
55 fn from(range: RangeKey<T>) -> Self {
56 Self {
57 start: range.start,
58 end: range.end,
59 }
60 }
61}