gfx_memory/allocator/
mod.rs

1//! This module provides `Allocator` trait and few allocators that implements the trait.
2
3mod dedicated;
4mod general;
5mod linear;
6
7pub use self::{
8    dedicated::{DedicatedAllocator, DedicatedBlock},
9    general::{GeneralAllocator, GeneralBlock, GeneralConfig},
10    linear::{LinearAllocator, LinearBlock, LinearConfig},
11};
12use crate::{block::Block, memory::Memory, AtomSize, Size};
13use std::ptr::NonNull;
14
15/// Allocator kind.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
17pub enum Kind {
18    /// Memory object per allocation.
19    Dedicated,
20
21    /// General purpose allocator.
22    General,
23
24    /// Allocates linearly.
25    /// Fast and low overhead.
26    /// Suitable for one-time-use allocations.
27    Linear,
28}
29
30/// Allocator trait implemented for various allocators.
31pub trait Allocator<B: hal::Backend> {
32    /// Block type returned by allocator.
33    type Block: Block<B>;
34
35    /// Allocator kind.
36    const KIND: Kind;
37
38    /// Allocate block of memory.
39    /// On success returns allocated block and amount of memory consumed from device.
40    fn alloc(
41        &mut self,
42        device: &B::Device,
43        size: Size,
44        align: Size,
45    ) -> Result<(Self::Block, Size), hal::device::AllocationError>;
46
47    /// Free block of memory.
48    /// Returns amount of memory returned to the device.
49    fn free(&mut self, device: &B::Device, block: Self::Block) -> Size;
50}
51
52unsafe fn allocate_memory_helper<B: hal::Backend>(
53    device: &B::Device,
54    memory_type: hal::MemoryTypeId,
55    size: Size,
56    memory_properties: hal::memory::Properties,
57    non_coherent_atom_size: Option<AtomSize>,
58) -> Result<(Memory<B>, Option<NonNull<u8>>), hal::device::AllocationError> {
59    use hal::device::Device as _;
60
61    log::trace!("Raw allocation of size {} for type {:?}", size, memory_type);
62    let raw = device.allocate_memory(memory_type, size)?;
63
64    let ptr = if memory_properties.contains(hal::memory::Properties::CPU_VISIBLE) {
65        match device.map_memory(&raw, hal::memory::Segment::ALL) {
66            Ok(ptr) => NonNull::new(ptr),
67            Err(hal::device::MapError::OutOfMemory(error)) => {
68                device.free_memory(raw);
69                return Err(error.into());
70            }
71            Err(e) => panic!("Unexpected mapping failure: {:?}", e),
72        }
73    } else {
74        None
75    };
76
77    let memory = Memory::from_raw(raw, size, memory_properties, non_coherent_atom_size);
78
79    Ok((memory, ptr))
80}