Skip to content

Commit

Permalink
refactor: let wgpu-core impl. OOB as valid. err.
Browse files Browse the repository at this point in the history
This does not, in fact, remove any bounds checks in practice. It is now
a validation error, implemented by the previous commit.
  • Loading branch information
ErichDonGubler committed Jan 11, 2025
1 parent 5ea1a13 commit 4edd590
Showing 1 changed file with 1 addition and 54 deletions.
55 changes: 1 addition & 54 deletions wgpu/src/api/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,6 @@ impl Buffer {
/// end of the buffer.
pub fn slice<S: RangeBounds<BufferAddress>>(&self, bounds: S) -> BufferSlice<'_> {
let (offset, size) = range_to_offset_size(bounds);
check_buffer_bounds(self.size, offset, size);
BufferSlice {
buffer: self,
offset,
Expand Down Expand Up @@ -645,31 +644,6 @@ impl Drop for BufferViewMut<'_> {
}
}

fn check_buffer_bounds(
buffer_size: BufferAddress,
offset: BufferAddress,
size: Option<BufferSize>,
) {
// A slice of length 0 is invalid, so the offset must not be equal to or greater than the buffer size.
if offset >= buffer_size {
panic!(
"slice offset {} is out of range for buffer of size {}",
offset, buffer_size
);
}

if let Some(size) = size {
// Detect integer overflow.
let end = offset.checked_add(size.get());
if end.map_or(true, |end| end > buffer_size) {
panic!(
"slice offset {} size {} is out of range for buffer of size {}",
offset, size, buffer_size
);
}
}
}

fn range_to_offset_size<S: RangeBounds<BufferAddress>>(
bounds: S,
) -> (BufferAddress, Option<BufferSize>) {
Expand All @@ -690,7 +664,7 @@ fn range_to_offset_size<S: RangeBounds<BufferAddress>>(

#[cfg(test)]
mod tests {
use super::{check_buffer_bounds, range_to_offset_size, BufferSize};
use super::{range_to_offset_size, BufferSize};

#[test]
fn range_to_offset_size_works() {
Expand All @@ -713,31 +687,4 @@ mod tests {
fn range_to_offset_size_panics_for_unbounded_empty_range() {
range_to_offset_size(..0);
}

#[test]
#[should_panic]
fn check_buffer_bounds_panics_for_offset_at_size() {
check_buffer_bounds(100, 100, None);
}

#[test]
fn check_buffer_bounds_works_for_end_in_range() {
check_buffer_bounds(200, 100, BufferSize::new(50));
check_buffer_bounds(200, 100, BufferSize::new(100));
check_buffer_bounds(u64::MAX, u64::MAX - 100, BufferSize::new(100));
check_buffer_bounds(u64::MAX, 0, BufferSize::new(u64::MAX));
check_buffer_bounds(u64::MAX, 1, BufferSize::new(u64::MAX - 1));
}

#[test]
#[should_panic]
fn check_buffer_bounds_panics_for_end_over_size() {
check_buffer_bounds(200, 100, BufferSize::new(101));
}

#[test]
#[should_panic]
fn check_buffer_bounds_panics_for_end_wraparound() {
check_buffer_bounds(u64::MAX, 1, BufferSize::new(u64::MAX));
}
}

0 comments on commit 4edd590

Please sign in to comment.