rendy_memory/mapping/
write.rs

1use std::ptr::copy_nonoverlapping;
2
3/// Trait for memory region suitable for host writes.
4pub trait Write<T: Copy> {
5    /// Get mutable slice of `T` bound to mapped range.
6    ///
7    /// # Safety
8    ///
9    /// * Returned slice should not be read.
10    unsafe fn slice(&mut self) -> &mut [T];
11
12    /// Write data into mapped memory sub-region.
13    ///
14    /// # Panic
15    ///
16    /// Panics if `data.len()` is greater than this sub-region len.
17    fn write(&mut self, data: &[T]) {
18        unsafe {
19            let slice = self.slice();
20            assert!(data.len() <= slice.len());
21            copy_nonoverlapping(data.as_ptr(), slice.as_mut_ptr(), data.len());
22        }
23    }
24}
25
26#[derive(Debug)]
27pub(super) struct WriteFlush<'a, T, F: FnOnce() + 'a> {
28    pub(super) slice: &'a mut [T],
29    pub(super) flush: Option<F>,
30}
31
32impl<'a, T, F> Drop for WriteFlush<'a, T, F>
33where
34    T: 'a,
35    F: FnOnce() + 'a,
36{
37    fn drop(&mut self) {
38        if let Some(f) = self.flush.take() {
39            f();
40        }
41    }
42}
43
44impl<'a, T, F> Write<T> for WriteFlush<'a, T, F>
45where
46    T: Copy + 'a,
47    F: FnOnce() + 'a,
48{
49    /// # Safety
50    ///
51    /// [See doc comment for trait method](trait.Write#method.slice)
52    unsafe fn slice(&mut self) -> &mut [T] {
53        self.slice
54    }
55}
56
57#[warn(dead_code)]
58#[derive(Debug)]
59pub(super) struct WriteCoherent<'a, T> {
60    pub(super) slice: &'a mut [T],
61}
62
63impl<'a, T> Write<T> for WriteCoherent<'a, T>
64where
65    T: Copy + 'a,
66{
67    /// # Safety
68    ///
69    /// [See doc comment for trait method](trait.Write#method.slice)
70    unsafe fn slice(&mut self) -> &mut [T] {
71        self.slice
72    }
73}