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
mod dedicated;
mod general;
mod linear;
pub use self::{
dedicated::{DedicatedAllocator, DedicatedBlock},
general::{GeneralAllocator, GeneralBlock, GeneralConfig},
linear::{LinearAllocator, LinearBlock, LinearConfig},
};
use crate::{block::Block, memory::Memory, AtomSize, Size};
use std::ptr::NonNull;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Kind {
Dedicated,
General,
Linear,
}
pub trait Allocator<B: hal::Backend> {
type Block: Block<B>;
const KIND: Kind;
fn alloc(
&mut self,
device: &B::Device,
size: Size,
align: Size,
) -> Result<(Self::Block, Size), hal::device::AllocationError>;
fn free(&mut self, device: &B::Device, block: Self::Block) -> Size;
}
unsafe fn allocate_memory_helper<B: hal::Backend>(
device: &B::Device,
memory_type: hal::MemoryTypeId,
size: Size,
memory_properties: hal::memory::Properties,
non_coherent_atom_size: Option<AtomSize>,
) -> Result<(Memory<B>, Option<NonNull<u8>>), hal::device::AllocationError> {
use hal::device::Device as _;
let raw = device.allocate_memory(memory_type, size)?;
let ptr = if memory_properties.contains(hal::memory::Properties::CPU_VISIBLE) {
match device.map_memory(&raw, hal::memory::Segment::ALL) {
Ok(ptr) => NonNull::new(ptr),
Err(hal::device::MapError::OutOfMemory(error)) => {
device.free_memory(raw);
return Err(error.into());
}
Err(e) => panic!("Unexpected mapping failure: {:?}", e),
}
} else {
None
};
let memory = Memory::from_raw(raw, size, memory_properties, non_coherent_atom_size);
Ok((memory, ptr))
}