gfx_memory/
lib.rs

1//! GPU memory management
2//!
3
4#![warn(
5    missing_docs,
6    trivial_casts,
7    trivial_numeric_casts,
8    unused_extern_crates,
9    unused_import_braces,
10    unused_qualifications
11)]
12#[allow(clippy::new_without_default)]
13mod allocator;
14mod block;
15mod heaps;
16mod mapping;
17mod memory;
18mod stats;
19mod usage;
20
21pub use crate::{
22    allocator::*,
23    block::Block,
24    heaps::{Heaps, HeapsError, MemoryBlock},
25    mapping::{MappedRange, Writer},
26    memory::Memory,
27    stats::*,
28    usage::MemoryUsage,
29};
30
31use std::ops::Range;
32
33/// Type for any memory sizes.
34pub type Size = u64;
35/// Type for non-coherent atom sizes.
36pub type AtomSize = std::num::NonZeroU64;
37
38fn is_non_coherent_visible(properties: hal::memory::Properties) -> bool {
39    properties.contains(hal::memory::Properties::CPU_VISIBLE)
40        && !properties.contains(hal::memory::Properties::COHERENT)
41}
42
43fn align_range(range: &Range<Size>, align: AtomSize) -> Range<Size> {
44    let start = range.start - range.start % align.get();
45    let end = ((range.end - 1) / align.get() + 1) * align.get();
46    start..end
47}
48
49fn align_size(size: Size, align: AtomSize) -> Size {
50    ((size - 1) / align.get() + 1) * align.get()
51}
52
53fn align_offset(value: Size, align: AtomSize) -> Size {
54    debug_assert_eq!(align.get().count_ones(), 1);
55    if value == 0 {
56        0
57    } else {
58        1 + ((value - 1) | (align.get() - 1))
59    }
60}
61
62fn segment_to_sub_range(
63    segment: hal::memory::Segment,
64    whole: &Range<Size>,
65) -> Result<Range<Size>, hal::device::MapError> {
66    let start = whole.start + segment.offset;
67    match segment.size {
68        Some(s) if start + s <= whole.end => Ok(start..start + s),
69        None if start < whole.end => Ok(start..whole.end),
70        _ => Err(hal::device::MapError::OutOfBounds),
71    }
72}
73
74fn is_sub_range(sub: &Range<Size>, range: &Range<Size>) -> bool {
75    sub.start >= range.start && sub.end <= range.end
76}