wgpu_hal/noop/
buffer.rs

1use alloc::vec::Vec;
2use core::{cell::UnsafeCell, ops::Range, ptr};
3
4use wgpu_sync::Arc;
5
6#[derive(Clone, Debug)]
7pub struct Buffer {
8    /// This data is potentially accessed mutably in arbitrary non-overlapping slices,
9    /// so we must store it in `UnsafeCell` to avoid making any too-strong no-aliasing claims.
10    storage: Arc<UnsafeCell<[u8]>>,
11
12    /// Size of the allocation.
13    ///
14    /// This is redundant with `storage.get().len()`, but that method is not
15    /// available until our MSRV is 1.79 or greater.
16    size: usize,
17}
18
19/// SAFETY:
20/// This shared mutable data will not be accessed in a way which causes data races;
21/// the obligation to do so is on the caller of the HAL API.
22/// For safe code, `wgpu-core` validation manages appropriate access.
23unsafe impl Send for Buffer {}
24unsafe impl Sync for Buffer {}
25
26impl Buffer {
27    pub(super) fn new(desc: &crate::BufferDescriptor) -> Result<Self, crate::DeviceError> {
28        let &crate::BufferDescriptor {
29            label: _,
30            size,
31            usage: _,
32            memory_flags: _,
33        } = desc;
34
35        let size = usize::try_from(size).map_err(|_| crate::DeviceError::OutOfMemory)?;
36
37        let mut vector: Vec<u8> = Vec::new();
38        vector
39            .try_reserve_exact(size)
40            .map_err(|_| crate::DeviceError::OutOfMemory)?;
41        vector.resize(size, 0);
42        let storage: Arc<[u8]> = Arc::from(vector);
43        debug_assert_eq!(storage.len(), size);
44
45        // SAFETY: `UnsafeCell<[u8]>` and `[u8]` have the same layout.
46        // This is just adding a wrapper type without changing any layout,
47        // because there is not currently a safe language/`std` way to accomplish this.
48        let storage: Arc<UnsafeCell<[u8]>> =
49            unsafe { Arc::from_raw(Arc::into_raw(storage) as *mut UnsafeCell<[u8]>) };
50
51        Ok(Buffer { storage, size })
52    }
53
54    /// Returns a pointer to the memory owned by this buffer within the given `range`.
55    ///
56    /// This may be used to create any number of simultaneous pointers;
57    /// aliasing is only a concern when actually reading, writing, or converting the pointer
58    /// to a reference.
59    pub(super) fn get_slice_ptr(&self, range: crate::MemoryRange) -> *mut [u8] {
60        let base_ptr = self.storage.get();
61        let range = range_to_usize(range, self.size);
62
63        // We must obtain a slice pointer without ever creating a slice reference
64        // that could alias with another slice.
65        ptr::slice_from_raw_parts_mut(
66            // SAFETY: `range_to_usize` bounds checks this addition.
67            unsafe { base_ptr.cast::<u8>().add(range.start) },
68            range.len(),
69        )
70    }
71}
72
73/// Convert a [`crate::MemoryRange`] to `Range<usize>` and bounds check it.
74fn range_to_usize(range: crate::MemoryRange, upper_bound: usize) -> Range<usize> {
75    // Note: these assertions should be impossible to trigger from safe code.
76    // We're doing them anyway since this entire backend is for testing
77    // (except for when it is an unused placeholder)
78    let start = usize::try_from(range.start).expect("range too large");
79    let end = usize::try_from(range.end).expect("range too large");
80    assert!(start <= end && end <= upper_bound, "range out of bounds");
81    start..end
82}