From bb83a5824a5c84f315c62368eac1bdaf69d82b90 Mon Sep 17 00:00:00 2001 From: "N.E.C." Date: Sun, 3 May 2026 13:40:29 -0700 Subject: [PATCH] Allow empty buffer slices to be instantiated (#8505) --- CHANGELOG.md | 27 +++ tests/tests/wgpu-gpu/buffer.rs | 149 +++++++++------ .../tests/wgpu-validation/api/buffer_slice.rs | 6 +- .../api/command_buffer_actions.rs | 13 -- wgpu-hal/src/gles/adapter.rs | 15 +- wgpu-hal/src/gles/device.rs | 75 +++++--- wgpu-hal/src/gles/mod.rs | 4 + wgpu/src/api/buffer.rs | 169 +++++++++--------- wgpu/src/api/command_buffer_actions.rs | 10 +- wgpu/src/api/render_bundle_encoder.rs | 14 +- wgpu/src/api/render_pass.rs | 14 +- wgpu/src/util/mod.rs | 2 +- 12 files changed, 297 insertions(+), 201 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c94b7aa22..d9cd1cf89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,6 +85,33 @@ GLSL: By @andyleiserson in [#9321](https://github.com/gfx-rs/wgpu/pull/9321). +#### Empty buffer slices are now permitted + +Creating a `BufferSlice` with a length of 0 no longer causes a panic. + +Empty buffer slices can be: + +- Instantiated +- Mapped (the result is an empty slice of bytes) + +Empty buffer slices cannot be: + +- Used in buffer bindings +- Passed to `set_index_buffer` or `set_vertex_buffer` + +#3170 tracks making it possible to pass a zero-size `BufferSlice` to `set_vertex_buffer` and `set_index_buffer` in the future. + +Zero-size buffer bindings are still not permitted. `BufferBinding` now implements `TryFrom` instead of `From`. The `TryFrom` conversion will fail if the slice is zero-size. + +```diff +-let slice = buffer.slice(0..0); // panic! +-let mapping = BufferBinding::from(slice); // infallible ++let slice = buffer.slice(0..0); // okay ++let mapping = BufferBinding::try_from(slice).unwrap(); // panic +``` + +By @beholdnec in [#8505](https://github.com/gfx-rs/wgpu/pull/8505). + ### Added/New Features #### General diff --git a/tests/tests/wgpu-gpu/buffer.rs b/tests/tests/wgpu-gpu/buffer.rs index c1c592d02..1c8076a0f 100644 --- a/tests/tests/wgpu-gpu/buffer.rs +++ b/tests/tests/wgpu-gpu/buffer.rs @@ -4,7 +4,8 @@ use wgpu_test::{ pub fn all_tests(vec: &mut Vec) { vec.extend([ - EMPTY_BUFFER, + EMPTY_BUFFER_READ, + EMPTY_BUFFER_READ_WRITE, MAP_OFFSET, MAP_WITHOUT_SUBMIT, MINIMUM_BUFFER_BINDING_SIZE_LAYOUT, @@ -14,19 +15,72 @@ pub fn all_tests(vec: &mut Vec) { ]); } -async fn test_empty_buffer_range(ctx: &TestingContext, buffer_size: u64, label: &str) { - let r = wgpu::BufferUsages::MAP_READ; - let rw = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::MAP_WRITE; - for usage in [r, rw] { - let b0 = ctx.device.create_buffer(&wgpu::BufferDescriptor { - label: Some(label), - size: buffer_size, - usage, - mapped_at_creation: false, - }); +async fn test_empty_buffer_range_with_usage( + ctx: &TestingContext, + buffer_size: u64, + label: &str, + usage: wgpu::BufferUsages, +) { + let b0 = ctx.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: buffer_size, + usage, + mapped_at_creation: false, + }); + b0.slice(0..0) + .map_async(wgpu::MapMode::Read, Result::unwrap); + + ctx.async_poll(wgpu::PollType::wait_indefinitely()) + .await + .unwrap(); + + { + let view = b0.slice(0..0).get_mapped_range().unwrap(); + assert!(view.is_empty()); + } + + b0.unmap(); + + // Map and unmap right away. + b0.slice(0..0).map_async(wgpu::MapMode::Read, move |_| {}); + b0.unmap(); + + // Map multiple times before unmapping. + b0.slice(0..0).map_async(wgpu::MapMode::Read, move |_| {}); + b0.slice(0..0) + .map_async(wgpu::MapMode::Read, move |result| { + assert!(result.is_err()); + }); + b0.slice(0..0) + .map_async(wgpu::MapMode::Read, move |result| { + assert!(result.is_err()); + }); + b0.slice(0..0) + .map_async(wgpu::MapMode::Read, move |result| { + assert!(result.is_err()); + }); + b0.unmap(); + + // Ensure mapping errors didn't break it permanently. + b0.slice(0..0) + .map_async(wgpu::MapMode::Read, Result::unwrap); + + ctx.async_poll(wgpu::PollType::wait_indefinitely()) + .await + .unwrap(); + + { + let view = b0.slice(0..0).get_mapped_range().unwrap(); + assert!(view.is_empty()); + } + + b0.unmap(); + + // Write mode. + if usage.contains(wgpu::BufferUsages::MAP_WRITE) { b0.slice(0..0) - .map_async(wgpu::MapMode::Read, Result::unwrap); + .map_async(wgpu::MapMode::Write, Result::unwrap); ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await @@ -37,60 +91,35 @@ async fn test_empty_buffer_range(ctx: &TestingContext, buffer_size: u64, label: assert!(view.is_empty()); } + { + let view = b0.slice(0..0).get_mapped_range_mut().unwrap(); + assert!(view.is_empty()); + } + b0.unmap(); // Map and unmap right away. - b0.slice(0..0).map_async(wgpu::MapMode::Read, move |_| {}); + b0.slice(0..0) + .map_async(wgpu::MapMode::Write, Result::unwrap); b0.unmap(); - - // Map multiple times before unmapping. - b0.slice(0..0).map_async(wgpu::MapMode::Read, move |_| {}); - b0.slice(0..0) - .map_async(wgpu::MapMode::Read, move |result| { - assert!(result.is_err()); - }); - b0.slice(0..0) - .map_async(wgpu::MapMode::Read, move |result| { - assert!(result.is_err()); - }); - b0.slice(0..0) - .map_async(wgpu::MapMode::Read, move |result| { - assert!(result.is_err()); - }); - b0.unmap(); - - // Write mode. - if usage == rw { - b0.slice(0..0) - .map_async(wgpu::MapMode::Write, Result::unwrap); - - ctx.async_poll(wgpu::PollType::wait_indefinitely()) - .await - .unwrap(); - - //{ - // let view = b0.slice(0..0).get_mapped_range_mut(); - // assert!(view.is_empty()); - //} - - b0.unmap(); - - // Map and unmap right away. - b0.slice(0..0).map_async(wgpu::MapMode::Write, move |_| {}); - b0.unmap(); - } } + // Test buffer mapped at creation. let b1 = ctx.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: buffer_size, - usage: rw, + usage, mapped_at_creation: true, }); { + let view = b1.slice(0..0).get_mapped_range().unwrap(); + assert!(view.is_empty()); + } + + if usage.contains(wgpu::BufferUsages::MAP_WRITE) { let view = b1.slice(0..0).get_mapped_range_mut().unwrap(); - assert_eq!(view.len(), 0); + assert!(view.is_empty()); } b1.unmap(); @@ -101,15 +130,25 @@ async fn test_empty_buffer_range(ctx: &TestingContext, buffer_size: u64, label: } #[gpu_test] -static EMPTY_BUFFER: GpuTestConfiguration = GpuTestConfiguration::new() +static EMPTY_BUFFER_READ: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters(TestParameters::default().enable_noop()) + .run_async(|ctx| async move { + let usage = wgpu::BufferUsages::MAP_READ; + test_empty_buffer_range_with_usage(&ctx, 2048, "regular buffer", usage).await; + test_empty_buffer_range_with_usage(&ctx, 0, "zero-sized buffer", usage).await; + }); + +#[gpu_test] +static EMPTY_BUFFER_READ_WRITE: GpuTestConfiguration = GpuTestConfiguration::new() .parameters( TestParameters::default() .expect_fail(FailureCase::always()) .enable_noop(), ) .run_async(|ctx| async move { - test_empty_buffer_range(&ctx, 2048, "regular buffer").await; - test_empty_buffer_range(&ctx, 0, "zero-sized buffer").await; + let usage = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::MAP_WRITE; + test_empty_buffer_range_with_usage(&ctx, 2048, "regular buffer", usage).await; + test_empty_buffer_range_with_usage(&ctx, 0, "zero-sized buffer", usage).await; }); #[gpu_test] diff --git a/tests/tests/wgpu-validation/api/buffer_slice.rs b/tests/tests/wgpu-validation/api/buffer_slice.rs index ac9fe9f8d..cfc0d9583 100644 --- a/tests/tests/wgpu-validation/api/buffer_slice.rs +++ b/tests/tests/wgpu-validation/api/buffer_slice.rs @@ -36,7 +36,7 @@ fn getters() { slice_with_size.offset(), slice_with_size.size() ), - (&buffer, 10, NonZero::new(80).unwrap()) + (&buffer, 10, 80) ); let slice_without_size = buffer.slice(10..); @@ -46,7 +46,7 @@ fn getters() { slice_without_size.offset(), slice_without_size.size() ), - (&buffer, 10, NonZero::new(90).unwrap()) + (&buffer, 10, 90) ); } @@ -60,7 +60,7 @@ fn into_buffer_binding() { buffer: b, offset: 50, size: Some(size), - }) = wgpu::BindingResource::from(buffer.slice(50..80)) + }) = buffer.slice(50..80).try_into().unwrap() else { panic!("didn't match") }; diff --git a/tests/tests/wgpu-validation/api/command_buffer_actions.rs b/tests/tests/wgpu-validation/api/command_buffer_actions.rs index 24b5ac255..66c4e0b15 100644 --- a/tests/tests/wgpu-validation/api/command_buffer_actions.rs +++ b/tests/tests/wgpu-validation/api/command_buffer_actions.rs @@ -41,19 +41,6 @@ fn encoder_map_buffer_on_submit_defers_until_submit() { assert!(fired.load(SeqCst)); } -/// Empty ranges panic immediately when registering the deferred map. -#[test] -#[should_panic = "buffer slices can not be empty"] -fn encoder_map_buffer_on_submit_empty_range_panics_immediately() { - let (device, _queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default()); - let buffer = make_read_buffer(&device, 16); - - let encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - - // This panics inside map_buffer_on_submit (range_to_offset_size). - encoder.map_buffer_on_submit(&buffer, wgpu::MapMode::Read, 8..8, |_| {}); -} - /// Out-of-bounds ranges panic during submit (when the deferred map executes). #[test] #[should_panic = "is out of range for buffer of size"] diff --git a/wgpu-hal/src/gles/adapter.rs b/wgpu-hal/src/gles/adapter.rs index d8f14d42e..246384b80 100644 --- a/wgpu-hal/src/gles/adapter.rs +++ b/wgpu-hal/src/gles/adapter.rs @@ -1317,14 +1317,17 @@ impl super::AdapterShared { } else { log::error!("Fake map"); let length = dst_data.len(); - let buffer_mapping = - unsafe { gl.map_buffer_range(target, offset, length as _, glow::MAP_READ_BIT) }; + // glMapBufferRange throws an error if length is 0. + if length != 0 { + let buffer_mapping = + unsafe { gl.map_buffer_range(target, offset, length as _, glow::MAP_READ_BIT) }; - unsafe { - core::ptr::copy_nonoverlapping(buffer_mapping, dst_data.as_mut_ptr(), length) - }; + unsafe { + core::ptr::copy_nonoverlapping(buffer_mapping, dst_data.as_mut_ptr(), length) + }; - unsafe { gl.unmap_buffer(target) }; + unsafe { gl.unmap_buffer(target) }; + } } } } diff --git a/wgpu-hal/src/gles/device.rs b/wgpu-hal/src/gles/device.rs index 1f63a8081..8a5bae7be 100644 --- a/wgpu-hal/src/gles/device.rs +++ b/wgpu-hal/src/gles/device.rs @@ -579,6 +579,7 @@ impl crate::Device for super::Device { target, size: desc.size, map_flags: 0, + mapped: false.into(), data: Some(Arc::new(MaybeMutex::new(vec![0; desc.size as usize]))), offset_of_current_mapping: Arc::new(MaybeMutex::new(0)), }); @@ -678,6 +679,7 @@ impl crate::Device for super::Device { raw, target, size: desc.size, + mapped: false.into(), map_flags, data, offset_of_current_mapping: Arc::new(MaybeMutex::new(0)), @@ -719,13 +721,28 @@ impl crate::Device for super::Device { slice.as_mut_ptr() } else { *lock(&buffer.offset_of_current_mapping) = range.start; - unsafe { - gl.map_buffer_range( - buffer.target, - range.start as i32, - (range.end - range.start) as i32, - buffer.map_flags, - ) + // glMapBufferRange throws an error if length is 0. + // We want to allow mapping 0-sized buffer slices, so perform a workaround + // if the range length is 0. The resulting pointer must never be dereferenced. + let range_start: i32 = range + .start + .try_into() + .expect("Buffer range invalid for GLES"); + let range_length: i32 = (range.end - range.start) + .try_into() + .expect("Buffer range invalid for GLES"); + if range_length != 0 { + buffer.mapped.set(true); + unsafe { + gl.map_buffer_range( + buffer.target, + range_start, + range_length, + buffer.map_flags, + ) + } + } else { + ptr::dangling_mut() } }; unsafe { gl.bind_buffer(buffer.target, None) }; @@ -738,13 +755,15 @@ impl crate::Device for super::Device { }) } unsafe fn unmap_buffer(&self, buffer: &super::Buffer) { - if let Some(raw) = buffer.raw { - if buffer.data.is_none() { - let gl = &self.shared.context.lock(); - unsafe { gl.bind_buffer(buffer.target, Some(raw)) }; - unsafe { gl.unmap_buffer(buffer.target) }; - unsafe { gl.bind_buffer(buffer.target, None) }; - *lock(&buffer.offset_of_current_mapping) = 0; + if buffer.mapped.replace(false) { + if let Some(raw) = buffer.raw { + if buffer.data.is_none() { + let gl = &self.shared.context.lock(); + unsafe { gl.bind_buffer(buffer.target, Some(raw)) }; + unsafe { gl.unmap_buffer(buffer.target) }; + unsafe { gl.bind_buffer(buffer.target, None) }; + *lock(&buffer.offset_of_current_mapping) = 0; + } } } } @@ -752,19 +771,21 @@ impl crate::Device for super::Device { where I: Iterator, { - if let Some(raw) = buffer.raw { - if buffer.data.is_none() { - let gl = &self.shared.context.lock(); - unsafe { gl.bind_buffer(buffer.target, Some(raw)) }; - for range in ranges { - let offset_of_current_mapping = *lock(&buffer.offset_of_current_mapping); - unsafe { - gl.flush_mapped_buffer_range( - buffer.target, - (range.start - offset_of_current_mapping) as i32, - (range.end - range.start) as i32, - ) - }; + if buffer.mapped.get() { + if let Some(raw) = buffer.raw { + if buffer.data.is_none() { + let gl = &self.shared.context.lock(); + unsafe { gl.bind_buffer(buffer.target, Some(raw)) }; + for range in ranges { + let offset_of_current_mapping = *lock(&buffer.offset_of_current_mapping); + unsafe { + gl.flush_mapped_buffer_range( + buffer.target, + (range.start - offset_of_current_mapping) as i32, + (range.end - range.start) as i32, + ) + }; + } } } } diff --git a/wgpu-hal/src/gles/mod.rs b/wgpu-hal/src/gles/mod.rs index 1a0292d4a..fc090e177 100644 --- a/wgpu-hal/src/gles/mod.rs +++ b/wgpu-hal/src/gles/mod.rs @@ -115,6 +115,7 @@ pub use self::wgl::{Instance, Surface}; use alloc::{boxed::Box, string::String, string::ToString as _, sync::Arc, vec::Vec}; use core::{ + cell::Cell, fmt, ops::Range, sync::atomic::{AtomicU32, AtomicU8}, @@ -344,6 +345,9 @@ pub struct Buffer { size: wgt::BufferAddress, /// Flags to use within calls to [`Device::map_buffer`](crate::Device::map_buffer). map_flags: u32, + /// True if the GL buffer is actually mapped, i.e. not "fake-mapped" with + /// an empty slice + mapped: Cell, data: Option>>>, offset_of_current_mapping: Arc>, } diff --git a/wgpu/src/api/buffer.rs b/wgpu/src/api/buffer.rs index 786ba77ac..3f1c7e661 100644 --- a/wgpu/src/api/buffer.rs +++ b/wgpu/src/api/buffer.rs @@ -1,6 +1,7 @@ use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; use core::{ error, fmt, + num::NonZero, ops::{Bound, Deref, Range, RangeBounds}, }; @@ -307,7 +308,6 @@ impl Buffer { /// # Panics /// /// - If `bounds` is outside of the bounds of `self`. - /// - If `bounds` has a length less than 1. #[track_caller] pub fn slice>(&self, bounds: S) -> BufferSlice<'_> { let (offset, size) = range_to_offset_size(bounds, self.size); @@ -477,7 +477,7 @@ impl Buffer { /// You can pass buffer slices to methods like [`RenderPass::set_vertex_buffer`] /// and [`RenderPass::set_index_buffer`] to indicate which portion of the buffer /// a draw call should consult. You can also convert it to a [`BufferBinding`] -/// with `.into()`. +/// with `.try_into()`, which fails if the slice length is 0. /// /// To access the slice's contents on the CPU, you must first [map] the buffer, /// and then call [`BufferSlice::get_mapped_range`] or @@ -501,7 +501,7 @@ impl Buffer { pub struct BufferSlice<'a> { pub(crate) buffer: &'a Buffer, pub(crate) offset: BufferAddress, - pub(crate) size: BufferSize, + pub(crate) size: BufferAddress, } #[cfg(send_sync)] static_assertions::assert_impl_all!(BufferSlice<'_>: Send, Sync); @@ -518,11 +518,10 @@ impl<'a> BufferSlice<'a> { /// # Panics /// /// - If `bounds` is outside of the bounds of `self`. - /// - If `bounds` has a length less than 1. #[track_caller] pub fn slice>(&self, bounds: S) -> BufferSlice<'a> { - let (offset, size) = range_to_offset_size(bounds, self.size.get()); - check_buffer_bounds(self.size.get(), offset, size); + let (offset, size) = range_to_offset_size(bounds, self.size); + check_buffer_bounds(self.size, offset, size); BufferSlice { buffer: self.buffer, offset: self.offset + offset, // check_buffer_bounds ensures this does not overflow @@ -557,7 +556,6 @@ impl<'a> BufferSlice<'a> { /// /// # Panics /// - /// - If the buffer is already mapped. /// - If the buffer’s [`BufferUsages`] do not allow the requested [`MapMode`]. /// - If the beginning of this slice is not aligned to [`MAP_ALIGNMENT`] within the buffer. /// - If the length of this slice is not a multiple of 4. @@ -575,9 +573,15 @@ impl<'a> BufferSlice<'a> { callback: impl FnOnce(Result<(), BufferAsyncError>) + WasmNotSend + 'static, ) { let mut mc = self.buffer.map_context.lock(); - assert_eq!(mc.mapped_range, 0..0, "Buffer is already mapped"); - let end = self.offset + self.size.get(); - mc.mapped_range = self.offset..end; + if mc.mapped_range.is_some() { + // Buffer is already mapped; fail + drop(mc); + callback(Err(BufferAsyncError)); + return; + } + + let end = self.offset + self.size; + mc.mapped_range = Some(self.offset..end); drop(mc); // release the lock of map_context as callback can call lock it again self.buffer @@ -662,28 +666,38 @@ impl<'a> BufferSlice<'a> { } /// Returns the size of this slice. - pub fn size(&self) -> BufferSize { + pub fn size(&self) -> BufferAddress { self.size } -} -impl<'a> From> for crate::BufferBinding<'a> { - /// Convert a [`BufferSlice`] to an equivalent [`BufferBinding`], - /// provided that it will be used without a dynamic offset. - fn from(value: BufferSlice<'a>) -> Self { - BufferBinding { - buffer: value.buffer, - offset: value.offset, - size: Some(value.size), - } + pub(crate) fn size_expect_nonzero(&self) -> BufferSize { + BufferSize::new(self.size).expect("buffer slice can not be empty") } } -impl<'a> From> for crate::BindingResource<'a> { +impl<'a> TryFrom> for crate::BufferBinding<'a> { + type Error = (); + + /// Convert a [`BufferSlice`] to an equivalent [`BufferBinding`], + /// provided that it will be used without a dynamic offset. + fn try_from(value: BufferSlice<'a>) -> Result { + Ok(BufferBinding { + buffer: value.buffer, + offset: value.offset, + size: Some(NonZero::new(value.size()).ok_or(())?), + }) + } +} + +impl<'a> TryFrom> for crate::BindingResource<'a> { + type Error = (); + /// Convert a [`BufferSlice`] to an equivalent [`BindingResource::Buffer`], /// provided that it will be used without a dynamic offset. - fn from(value: BufferSlice<'a>) -> Self { - crate::BindingResource::Buffer(crate::BufferBinding::from(value)) + fn try_from(value: BufferSlice<'a>) -> Result { + Ok(crate::BindingResource::Buffer( + crate::BufferBinding::try_from(value)?, + )) } } @@ -720,9 +734,9 @@ struct Subrange { } impl Subrange { - fn new(offset: BufferAddress, size: BufferSize, kind: RangeMappingKind) -> Self { + fn new(offset: BufferAddress, size: BufferAddress, kind: RangeMappingKind) -> Self { Self { - index: offset..(offset + size.get()), + index: offset..(offset + size), kind, } } @@ -745,13 +759,12 @@ impl fmt::Display for Subrange { pub(crate) struct MapContext { /// The range of the buffer that is mapped. /// - /// This is `0..0` if the buffer is not mapped. This becomes non-empty when - /// the buffer is mapped at creation time, and when you call `map_async` on - /// some [`BufferSlice`] (so technically, it indicates the portion that is - /// *or has been requested to be* mapped.) + /// This becomes Some(...) when the buffer is mapped at creation time, and + /// when you call `map_async` on some [`BufferSlice`] (so technically, it + /// indicates the portion that is *or has been requested to be* mapped.) /// /// All [`BufferView`]s and [`BufferViewMut`]s must fall within this range. - mapped_range: Range, + mapped_range: Option>, /// The ranges covered by all outstanding [`BufferView`]s and /// [`BufferViewMut`]s. These are non-overlapping, and are all contained @@ -768,14 +781,14 @@ impl MapContext { /// [`mapped_at_creation`]: BufferDescriptor::mapped_at_creation pub(crate) fn new(mapped_range: Option>) -> Self { Self { - mapped_range: mapped_range.unwrap_or(0..0), + mapped_range, sub_ranges: Vec::new(), } } /// Record that the buffer is no longer mapped. fn reset(&mut self) { - self.mapped_range = 0..0; + self.mapped_range = None; assert!( self.sub_ranges.is_empty(), @@ -789,18 +802,19 @@ impl MapContext { /// /// This returns an error if the given range is invalid. fn validate_and_add(&mut self, new_sub: Subrange) -> Result<(), MapRangeError> { - if self.mapped_range.is_empty() { + if self.mapped_range.is_none() { return Err(MapRangeError( "tried to call get_mapped_range(_mut) on an unmapped buffer".into(), )); } - if !range_contains(&self.mapped_range, &new_sub.index) { + let mapped_range = self.mapped_range.as_ref().unwrap(); + if !range_contains(mapped_range, &new_sub.index) { return Err(MapRangeError(alloc::format!( "tried to call get_mapped_range(_mut) on a range that is not entirely mapped. \ Attempted to get range {}, but the mapped range is {}..{}", new_sub, - self.mapped_range.start, - self.mapped_range.end + mapped_range.start, + mapped_range.end ))); } // This check is essential for avoiding undefined behavior: it is the @@ -829,8 +843,8 @@ impl MapContext { /// /// This panics if the given range does not exactly match one previously /// passed to [`MapContext::validate_and_add`]. - pub(crate) fn remove(&mut self, offset: BufferAddress, size: BufferSize) { - let end = offset + size.get(); + pub(crate) fn remove(&mut self, offset: BufferAddress, size: BufferAddress) { + let end = offset + size; let index = self .sub_ranges @@ -911,7 +925,7 @@ pub struct BufferView { // `buffer, offset, size` are similar to `BufferSlice`, except that they own the buffer. buffer: Buffer, offset: BufferAddress, - size: BufferSize, + size: BufferAddress, inner: dispatch::DispatchBufferMappedRange, } @@ -937,7 +951,7 @@ pub struct BufferViewMut { // `buffer, offset, size` are similar to `BufferSlice`, except that they own the buffer. buffer: Buffer, offset: BufferAddress, - size: BufferSize, + size: BufferAddress, inner: dispatch::DispatchBufferMappedRange, } @@ -996,7 +1010,7 @@ impl BufferViewMut { /// Returns the length of this view; the number of bytes to be written. pub fn len(&self) -> usize { // cannot fail because we can't actually map more than isize::MAX bytes - usize::try_from(self.size.get()).unwrap() + usize::try_from(self.size).unwrap() } /// Returns `true` if the view has a length of 0. @@ -1027,24 +1041,23 @@ impl BufferViewMut { #[track_caller] fn check_buffer_bounds( - buffer_size: BufferAddress, + whole_size: BufferAddress, slice_offset: BufferAddress, - slice_size: BufferSize, + slice_size: BufferAddress, ) { - // A slice of length 0 is invalid, so the offset must not be equal to or greater than the buffer size. - if slice_offset >= buffer_size { + if slice_offset > whole_size { panic!( "slice offset {} is out of range for buffer of size {}", - slice_offset, buffer_size + slice_offset, whole_size ); } // Detect integer overflow. - let end = slice_offset.checked_add(slice_size.get()); - if end.is_none_or(|end| end > buffer_size) { + let end = slice_offset.checked_add(slice_size); + if end.is_none_or(|end| end > whole_size) { panic!( "slice offset {} size {} is out of range for buffer of size {}", - slice_offset, slice_size, buffer_size + slice_offset, slice_size, whole_size ); } } @@ -1053,75 +1066,59 @@ fn check_buffer_bounds( pub(crate) fn range_to_offset_size>( bounds: S, whole_size: BufferAddress, -) -> (BufferAddress, BufferSize) { +) -> (BufferAddress, BufferAddress) { let offset = match bounds.start_bound() { Bound::Included(&bound) => bound, Bound::Excluded(&bound) => bound + 1, Bound::Unbounded => 0, }; - let size = BufferSize::new(match bounds.end_bound() { + let size = match bounds.end_bound() { Bound::Included(&bound) => bound + 1 - offset, Bound::Excluded(&bound) => bound - offset, Bound::Unbounded => whole_size - offset, - }) - .expect("buffer slices can not be empty"); + }; (offset, size) } #[cfg(test)] mod tests { - use super::{ - check_buffer_bounds, range_overlaps, range_to_offset_size, BufferAddress, BufferSize, - }; - - fn bs(value: BufferAddress) -> BufferSize { - BufferSize::new(value).unwrap() - } + use super::{check_buffer_bounds, range_overlaps, range_to_offset_size}; #[test] fn range_to_offset_size_works() { let whole = 100; - assert_eq!(range_to_offset_size(0..2, whole), (0, bs(2))); - assert_eq!(range_to_offset_size(2..5, whole), (2, bs(3))); - assert_eq!(range_to_offset_size(.., whole), (0, bs(whole))); - assert_eq!(range_to_offset_size(21.., whole), (21, bs(whole - 21))); - assert_eq!(range_to_offset_size(0.., whole), (0, bs(whole))); - assert_eq!(range_to_offset_size(..21, whole), (0, bs(21))); - } - - #[test] - #[should_panic = "buffer slices can not be empty"] - fn range_to_offset_size_panics_for_empty_range() { - range_to_offset_size(123..123, 200); - } - - #[test] - #[should_panic = "buffer slices can not be empty"] - fn range_to_offset_size_panics_for_unbounded_empty_range() { - range_to_offset_size(..0, 100); + assert_eq!(range_to_offset_size(0..2, whole), (0, 2)); + assert_eq!(range_to_offset_size(2..5, whole), (2, 3)); + assert_eq!(range_to_offset_size(.., whole), (0, whole)); + assert_eq!(range_to_offset_size(21.., whole), (21, whole - 21)); + assert_eq!(range_to_offset_size(0.., whole), (0, whole)); + assert_eq!(range_to_offset_size(..21, whole), (0, 21)); } #[test] fn check_buffer_bounds_works_for_end_in_range() { - check_buffer_bounds(200, 100, bs(50)); - check_buffer_bounds(200, 100, bs(100)); - check_buffer_bounds(u64::MAX, u64::MAX - 100, bs(100)); - check_buffer_bounds(u64::MAX, 0, bs(u64::MAX)); - check_buffer_bounds(u64::MAX, 1, bs(u64::MAX - 1)); + check_buffer_bounds(200, 100, 50); + check_buffer_bounds(200, 100, 100); + check_buffer_bounds(u64::MAX, u64::MAX - 100, 100); + check_buffer_bounds(u64::MAX, 0, u64::MAX); + check_buffer_bounds(u64::MAX, 1, u64::MAX - 1); + // Test empty buffer slices + check_buffer_bounds(0, 0, 0); + check_buffer_bounds(u64::MAX, u64::MAX, 0); } #[test] #[should_panic] fn check_buffer_bounds_panics_for_end_over_size() { - check_buffer_bounds(200, 100, bs(101)); + check_buffer_bounds(200, 100, 101); } #[test] #[should_panic] fn check_buffer_bounds_panics_for_end_wraparound() { - check_buffer_bounds(u64::MAX, 1, bs(u64::MAX)); + check_buffer_bounds(u64::MAX, 1, u64::MAX); } #[test] diff --git a/wgpu/src/api/command_buffer_actions.rs b/wgpu/src/api/command_buffer_actions.rs index 1c79b16ff..7cdbca97a 100644 --- a/wgpu/src/api/command_buffer_actions.rs +++ b/wgpu/src/api/command_buffer_actions.rs @@ -1,5 +1,4 @@ use alloc::{sync::Arc, vec::Vec}; -use core::num::NonZeroU64; use crate::{util::Mutex, *}; @@ -8,8 +7,8 @@ use crate::{util::Mutex, *}; pub(crate) struct DeferredBufferMapping { pub buffer: api::Buffer, pub mode: MapMode, - pub offset: u64, - pub size: NonZeroU64, + pub offset: BufferAddress, + pub size: BufferAddress, pub callback: dispatch::BufferMapCallback, } @@ -33,7 +32,7 @@ impl DeferredCommandBufferActions { for mapping in self.buffer_mappings { mapping.buffer.map_async( mapping.mode, - mapping.offset..mapping.offset + mapping.size.get(), + mapping.offset..mapping.offset + mapping.size, mapping.callback, ); } @@ -85,7 +84,6 @@ macro_rules! impl_deferred_command_buffer_actions { /// # Panics /// /// - If `bounds` is outside the bounds of `buffer`. - /// - If `bounds` has a length less than 1. /// /// # Panics During Submit /// @@ -93,7 +91,7 @@ macro_rules! impl_deferred_command_buffer_actions { /// - If the buffer’s [`BufferUsages`] do not allow the requested [`MapMode`]. /// - If `bounds` is outside of the bounds of `buffer`. /// - If `bounds` does not start at a multiple of [`MAP_ALIGNMENT`]. - /// - If `bounds` has a length that is not a multiple of 4 greater than 0. + /// - If `bounds` has a length that is not a multiple of 4. /// /// [q::s]: Queue::submit /// [i::p_a]: Instance::poll_all diff --git a/wgpu/src/api/render_bundle_encoder.rs b/wgpu/src/api/render_bundle_encoder.rs index dcc3b9f05..041b67cac 100644 --- a/wgpu/src/api/render_bundle_encoder.rs +++ b/wgpu/src/api/render_bundle_encoder.rs @@ -88,12 +88,17 @@ impl<'a> RenderBundleEncoder<'a> { /// /// Subsequent calls to [`draw_indexed`](RenderBundleEncoder::draw_indexed) on this [`RenderBundleEncoder`] will /// use `buffer` as the source index buffer. + /// + /// # Panics + /// + /// - If the buffer slice length is 0. pub fn set_index_buffer(&mut self, buffer_slice: BufferSlice<'a>, index_format: IndexFormat) { self.inner.set_index_buffer( &buffer_slice.buffer.inner, index_format, buffer_slice.offset, - Some(buffer_slice.size), + // TODO(https://github.com/gfx-rs/wgpu/issues/3170): Empty slices should be supported here + Some(buffer_slice.size_expect_nonzero()), ); } @@ -107,6 +112,10 @@ impl<'a> RenderBundleEncoder<'a> { /// /// [`draw`]: RenderBundleEncoder::draw /// [`draw_indexed`]: RenderBundleEncoder::draw_indexed + /// + /// # Panics + /// + /// - If the buffer slice length is 0. pub fn set_vertex_buffer<'b, B>(&mut self, slot: u32, buffer_slice: B) where Option>: From, @@ -117,7 +126,8 @@ impl<'a> RenderBundleEncoder<'a> { slot, Some(&buffer_slice.buffer.inner), buffer_slice.offset, - Some(buffer_slice.size), + // TODO(https://github.com/gfx-rs/wgpu/issues/3170): Empty slices should be supported here + Some(buffer_slice.size_expect_nonzero()), ); } else { self.inner.set_vertex_buffer(slot, None, 0, None); diff --git a/wgpu/src/api/render_pass.rs b/wgpu/src/api/render_pass.rs index 6050ed1da..719cbbd0b 100644 --- a/wgpu/src/api/render_pass.rs +++ b/wgpu/src/api/render_pass.rs @@ -100,12 +100,17 @@ impl RenderPass<'_> { /// /// Subsequent calls to [`draw_indexed`](RenderPass::draw_indexed) on this [`RenderPass`] will /// use `buffer` as the source index buffer. + /// + /// # Panics + /// + /// - If the buffer slice length is 0. pub fn set_index_buffer(&mut self, buffer_slice: BufferSlice<'_>, index_format: IndexFormat) { self.inner.set_index_buffer( &buffer_slice.buffer.inner, index_format, buffer_slice.offset, - Some(buffer_slice.size), + // TODO(https://github.com/gfx-rs/wgpu/issues/3170): Empty slices should be supported here + Some(buffer_slice.size_expect_nonzero()), ); } @@ -121,6 +126,10 @@ impl RenderPass<'_> { /// /// [`draw`]: RenderPass::draw /// [`draw_indexed`]: RenderPass::draw_indexed + /// + /// # Panics + /// + /// - If the buffer slice length is 0. pub fn set_vertex_buffer<'b, B>(&mut self, slot: u32, buffer_slice: B) where Option>: From, @@ -131,7 +140,8 @@ impl RenderPass<'_> { slot, Some(&buffer_slice.buffer.inner), buffer_slice.offset, - Some(buffer_slice.size), + // TODO(https://github.com/gfx-rs/wgpu/issues/3170): Empty slices should be supported here + Some(buffer_slice.size_expect_nonzero()), ); } else { self.inner.set_vertex_buffer(slot, None, 0, None); diff --git a/wgpu/src/util/mod.rs b/wgpu/src/util/mod.rs index 8e3d832bf..3d909912b 100644 --- a/wgpu/src/util/mod.rs +++ b/wgpu/src/util/mod.rs @@ -48,7 +48,7 @@ impl DownloadBuffer { buffer: &super::BufferSlice<'_>, callback: impl FnOnce(Result) + Send + 'static, ) { - let size = buffer.size.into(); + let size = buffer.size; let download = device.create_buffer(&super::BufferDescriptor { size,