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
use crate::error::{Error, Result};
use crate::tlsf::Tlsf;
/// TLSF allocator over an abstract range, e.g. descriptor slots inside a [`DescriptorHeap`](crate::DescriptorHeap)
/// or sub-ranges of a large buffer. No Vulkan memory is involved.
pub struct VirtualBlock(Tlsf);
/// A range handed out by a [`VirtualBlock`]. Must be returned to the block it came from.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct VirtualAllocation {
node: u32,
offset: u64,
}
impl VirtualAllocation {
#[inline]
pub fn offset(&self) -> u64 {
self.offset
}
}
impl VirtualBlock {
pub fn new(size: u64) -> Result<Self> {
if size == 0 {
return Err(Error::ZeroSize);
}
Ok(Self(Tlsf::new(size, 1)))
}
#[inline]
pub fn allocate(&mut self, size: u64, alignment: u64) -> Result<VirtualAllocation> {
if size == 0 {
return Err(Error::ZeroSize);
}
if !alignment.is_power_of_two() {
return Err(Error::InvalidAlignment(alignment));
}
let (node, offset) = self
.0
.allocate(size, alignment, 0)
.ok_or(Error::OutOfMemory)?;
Ok(VirtualAllocation { node, offset })
}
#[inline]
pub fn free(&mut self, allocation: VirtualAllocation) {
self.0.free(allocation.node);
}
#[inline]
pub fn allocation_size(&self, allocation: &VirtualAllocation) -> u64 {
self.0.allocation_size(allocation.node)
}
#[inline]
pub fn size(&self) -> u64 {
self.0.size()
}
#[inline]
pub fn free_bytes(&self) -> u64 {
self.0.free_bytes()
}
#[inline]
pub fn allocation_count(&self) -> u32 {
self.0.allocation_count()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Checks all internal invariants, panicking on corruption. Intended for tests.
#[doc(hidden)]
pub fn validate(&self) {
self.0.validate();
}
}