rendy_memory/mapping/
write.rs

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
use std::ptr::copy_nonoverlapping;

/// Trait for memory region suitable for host writes.
pub trait Write<T: Copy> {
    /// Get mutable slice of `T` bound to mapped range.
    ///
    /// # Safety
    ///
    /// * Returned slice should not be read.
    unsafe fn slice(&mut self) -> &mut [T];

    /// Write data into mapped memory sub-region.
    ///
    /// # Panic
    ///
    /// Panics if `data.len()` is greater than this sub-region len.
    fn write(&mut self, data: &[T]) {
        unsafe {
            let slice = self.slice();
            assert!(data.len() <= slice.len());
            copy_nonoverlapping(data.as_ptr(), slice.as_mut_ptr(), data.len());
        }
    }
}

#[derive(Debug)]
pub(super) struct WriteFlush<'a, T, F: FnOnce() + 'a> {
    pub(super) slice: &'a mut [T],
    pub(super) flush: Option<F>,
}

impl<'a, T, F> Drop for WriteFlush<'a, T, F>
where
    T: 'a,
    F: FnOnce() + 'a,
{
    fn drop(&mut self) {
        if let Some(f) = self.flush.take() {
            f();
        }
    }
}

impl<'a, T, F> Write<T> for WriteFlush<'a, T, F>
where
    T: Copy + 'a,
    F: FnOnce() + 'a,
{
    /// # Safety
    ///
    /// [See doc comment for trait method](trait.Write#method.slice)
    unsafe fn slice(&mut self) -> &mut [T] {
        self.slice
    }
}

#[warn(dead_code)]
#[derive(Debug)]
pub(super) struct WriteCoherent<'a, T> {
    pub(super) slice: &'a mut [T],
}

impl<'a, T> Write<T> for WriteCoherent<'a, T>
where
    T: Copy + 'a,
{
    /// # Safety
    ///
    /// [See doc comment for trait method](trait.Write#method.slice)
    unsafe fn slice(&mut self) -> &mut [T] {
        self.slice
    }
}