diff --git a/CHANGELOG.md b/CHANGELOG.md index f861b92b0..b09087da8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,7 @@ Bottom level categories: - Added more granular limits for mesh shaders. By @inner-daemons in [#8739](https://github.com/gfx-rs/wgpu/pull/8739). - Added new `InvalidWorkgroupSizeError`, which is now used by `DrawError::InvalidGroupSize` and `StageError::InvalidWorkgroupSize`. By @andyleiserson in [#9357](https://github.com/gfx-rs/wgpu/pull/9357). - Zero-size `Queue::write_buffer` now returns an error if the offset is invalid or the buffer lacks `COPY_DST`. By @39ali in [#9374](https://github.com/gfx-rs/wgpu/pull/9374). +- `Buffer::get_mapped_range` and variants now return `Result<_, MapRangeError>>` instead of panicking, in line with WebGPU spec. By @atlv24 in [#9281](https://github.com/gfx-rs/wgpu/pull/9281). #### Validation diff --git a/examples/features/src/big_compute_buffers/mod.rs b/examples/features/src/big_compute_buffers/mod.rs index 32e44058f..bd131cf52 100644 --- a/examples/features/src/big_compute_buffers/mod.rs +++ b/examples/features/src/big_compute_buffers/mod.rs @@ -85,7 +85,7 @@ pub async fn execute_gpu_inner( let mut data = Vec::new(); for staging_buffer in &staging_buffers { let slice = staging_buffer.slice(..); - let mapped = slice.get_mapped_range(); + let mapped = slice.get_mapped_range().unwrap(); let chunk: Vec = bytemuck::allocation::pod_collect_to_vec(&mapped); data.extend_from_slice(&chunk); drop(mapped); diff --git a/examples/features/src/cooperative_matrix/mod.rs b/examples/features/src/cooperative_matrix/mod.rs index 211d549bb..2e2042e74 100644 --- a/examples/features/src/cooperative_matrix/mod.rs +++ b/examples/features/src/cooperative_matrix/mod.rs @@ -411,7 +411,7 @@ async fn execute( .expect("Channel receive failed") .expect("Buffer mapping failed"); - let data = buffer_slice.get_mapped_range(); + let data = buffer_slice.get_mapped_range().unwrap(); // Convert result back to f32 for comparison let result: Vec = if use_f16 { diff --git a/examples/features/src/framework.rs b/examples/features/src/framework.rs index 2f629ea9d..a3c662e75 100644 --- a/examples/features/src/framework.rs +++ b/examples/features/src/framework.rs @@ -744,7 +744,7 @@ impl From> ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await .unwrap(); - let bytes = dst_buffer_slice.get_mapped_range().to_vec(); + let bytes = dst_buffer_slice.get_mapped_range().unwrap().to_vec(); wgpu_test::image::compare_image_output( dbg!(env!("CARGO_MANIFEST_DIR").to_string() + "/../../" + params.image_path), diff --git a/examples/features/src/hello_synchronization/mod.rs b/examples/features/src/hello_synchronization/mod.rs index 2cddbee4d..140da957b 100644 --- a/examples/features/src/hello_synchronization/mod.rs +++ b/examples/features/src/hello_synchronization/mod.rs @@ -185,7 +185,7 @@ async fn get_data( device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); receiver.recv_async().await.unwrap().unwrap(); let data: Vec = - bytemuck::allocation::pod_collect_to_vec(&buffer_slice.get_mapped_range()[..]); + bytemuck::allocation::pod_collect_to_vec(&buffer_slice.get_mapped_range().unwrap()[..]); output.copy_from_slice(&data); staging_buffer.unmap(); } diff --git a/examples/features/src/hello_workgroups/mod.rs b/examples/features/src/hello_workgroups/mod.rs index 61b6aef1d..d8a05078c 100644 --- a/examples/features/src/hello_workgroups/mod.rs +++ b/examples/features/src/hello_workgroups/mod.rs @@ -174,7 +174,7 @@ async fn get_data( device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); receiver.recv_async().await.unwrap().unwrap(); let data: Vec = - bytemuck::allocation::pod_collect_to_vec(&buffer_slice.get_mapped_range()[..]); + bytemuck::allocation::pod_collect_to_vec(&buffer_slice.get_mapped_range().unwrap()[..]); output.copy_from_slice(&data); staging_buffer.unmap(); } diff --git a/examples/features/src/mipmap/mod.rs b/examples/features/src/mipmap/mod.rs index 108413ded..142533842 100644 --- a/examples/features/src/mipmap/mod.rs +++ b/examples/features/src/mipmap/mod.rs @@ -417,11 +417,13 @@ impl crate::framework::Example for Example { let timestamp_view = query_sets .mapping_buffer .slice(..size_of::() as wgpu::BufferAddress) - .get_mapped_range(); + .get_mapped_range() + .unwrap(); let pipeline_stats_view = query_sets .mapping_buffer .slice(pipeline_statistics_offset()..) - .get_mapped_range(); + .get_mapped_range() + .unwrap(); // Convert the raw data into a useful structure let timestamp_data: &TimestampQueries = bytemuck::from_bytes(×tamp_view); let pipeline_stats_data: &PipelineStatisticsQueries = diff --git a/examples/features/src/render_to_texture/mod.rs b/examples/features/src/render_to_texture/mod.rs index e06c8d638..ed60f05e1 100644 --- a/examples/features/src/render_to_texture/mod.rs +++ b/examples/features/src/render_to_texture/mod.rs @@ -137,7 +137,7 @@ async fn run(_path: Option) { receiver.recv_async().await.unwrap().unwrap(); log::info!("Output buffer mapped."); { - let view = buffer_slice.get_mapped_range(); + let view = buffer_slice.get_mapped_range().unwrap(); texture_data.extend_from_slice(&view[..]); } log::info!("Image data copied to local."); diff --git a/examples/features/src/repeated_compute/mod.rs b/examples/features/src/repeated_compute/mod.rs index 4b3697c9b..929e30cc8 100644 --- a/examples/features/src/repeated_compute/mod.rs +++ b/examples/features/src/repeated_compute/mod.rs @@ -115,7 +115,7 @@ async fn compute(local_buffer: &mut [u32], context: &WgpuContext) { log::info!("Result received."); // NOW we can call get_mapped_range. { - let view = buffer_slice.get_mapped_range(); + let view = buffer_slice.get_mapped_range().unwrap(); let data: Vec = bytemuck::allocation::pod_collect_to_vec(&view); local_buffer.copy_from_slice(&data); } diff --git a/examples/features/src/storage_texture/mod.rs b/examples/features/src/storage_texture/mod.rs index fe54265d2..67a8e2f52 100644 --- a/examples/features/src/storage_texture/mod.rs +++ b/examples/features/src/storage_texture/mod.rs @@ -146,7 +146,7 @@ async fn run(_path: Option) { receiver.recv_async().await.unwrap().unwrap(); log::info!("Output buffer mapped"); { - let view = buffer_slice.get_mapped_range(); + let view = buffer_slice.get_mapped_range().unwrap(); texture_data.copy_from_slice(&view[..]); } log::info!("GPU data copied to local."); diff --git a/examples/features/src/timestamp_queries/mod.rs b/examples/features/src/timestamp_queries/mod.rs index c46a35d39..0e1f673dd 100644 --- a/examples/features/src/timestamp_queries/mod.rs +++ b/examples/features/src/timestamp_queries/mod.rs @@ -181,7 +181,8 @@ impl Queries { let timestamp_view = self .destination_buffer .slice(..(size_of::() as wgpu::BufferAddress * self.num_queries)) - .get_mapped_range(); + .get_mapped_range() + .unwrap(); bytemuck::allocation::pod_collect_to_vec(×tamp_view) }; diff --git a/examples/standalone/01_hello_compute/src/main.rs b/examples/standalone/01_hello_compute/src/main.rs index 4379fbe9a..b6559ae0f 100644 --- a/examples/standalone/01_hello_compute/src/main.rs +++ b/examples/standalone/01_hello_compute/src/main.rs @@ -245,7 +245,7 @@ fn main() { device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); // We can now read the data from the buffer. - let data = buffer_slice.get_mapped_range(); + let data = buffer_slice.get_mapped_range().unwrap(); // Convert the data back to f32 via an aligned copy. let result: Vec = bytemuck::allocation::pod_collect_to_vec(&data); diff --git a/tests/src/image.rs b/tests/src/image.rs index 8813bbae2..b24c48363 100644 --- a/tests/src/image.rs +++ b/tests/src/image.rs @@ -584,7 +584,7 @@ impl ReadbackBuffers { let expected_buffer_size = expected_bytes_per_row * (self.texture_height / block_height) * self.texture_depth_or_array_layers; - let data: BufferView = buffer_slice.get_mapped_range(); + let data: BufferView = buffer_slice.get_mapped_range().unwrap(); if expected_buffer_size as usize == data.len() { data.to_vec() } else { diff --git a/tests/tests/wgpu-gpu/bgra8unorm_storage.rs b/tests/tests/wgpu-gpu/bgra8unorm_storage.rs index 0d9f4f024..6d42eaacd 100644 --- a/tests/tests/wgpu-gpu/bgra8unorm_storage.rs +++ b/tests/tests/wgpu-gpu/bgra8unorm_storage.rs @@ -151,7 +151,7 @@ static BGRA8_UNORM_STORAGE: GpuTestConfiguration = GpuTestConfiguration::new() .unwrap(); { - let texels = buffer_slice.get_mapped_range(); + let texels = buffer_slice.get_mapped_range().unwrap(); assert_eq!(texels.len(), 256 * 256 * 4); for texel in texels.chunks(4) { assert_eq!(texel[0], 255); // b diff --git a/tests/tests/wgpu-gpu/bind_groups.rs b/tests/tests/wgpu-gpu/bind_groups.rs index 9444506a8..5d9f788ab 100644 --- a/tests/tests/wgpu-gpu/bind_groups.rs +++ b/tests/tests/wgpu-gpu/bind_groups.rs @@ -382,7 +382,7 @@ static BIND_GROUP_WITH_MAX_BINDING_INDEX: GpuTestConfiguration = GpuTestConfigur device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); assert_eq!( - &*readback.slice(..).get_mapped_range(), + &*readback.slice(..).get_mapped_range().unwrap(), &test_value.to_le_bytes() ); }); diff --git a/tests/tests/wgpu-gpu/binding_array/buffers.rs b/tests/tests/wgpu-gpu/binding_array/buffers.rs index 9ca606963..61ba386a4 100644 --- a/tests/tests/wgpu-gpu/binding_array/buffers.rs +++ b/tests/tests/wgpu-gpu/binding_array/buffers.rs @@ -156,6 +156,7 @@ async fn binding_array_buffers( }); buffer .get_mapped_range_mut(..) + .unwrap() .slice(0..4) .copy_from_slice(&data.0); buffer.unmap(); @@ -270,7 +271,7 @@ async fn binding_array_buffers( ctx.device.poll(PollType::wait_indefinitely()).unwrap(); - let data = slice.get_mapped_range(); + let data = slice.get_mapped_range().unwrap(); assert_eq!(&data[..], &*image); } diff --git a/tests/tests/wgpu-gpu/binding_array/samplers.rs b/tests/tests/wgpu-gpu/binding_array/samplers.rs index 329226b3a..8098e762f 100644 --- a/tests/tests/wgpu-gpu/binding_array/samplers.rs +++ b/tests/tests/wgpu-gpu/binding_array/samplers.rs @@ -267,7 +267,7 @@ async fn binding_array_samplers(ctx: TestingContext, partially_bound: bool) { readback_buffer.slice(..).map_async(MapMode::Read, |_| {}); ctx.device.poll(PollType::wait_indefinitely()).unwrap(); - let readback_buffer_slice = readback_buffer.slice(..).get_mapped_range(); + let readback_buffer_slice = readback_buffer.slice(..).get_mapped_range().unwrap(); assert_eq!(&readback_buffer_slice[0..8], &expected_output[..]); } diff --git a/tests/tests/wgpu-gpu/buffer.rs b/tests/tests/wgpu-gpu/buffer.rs index 2f08fd58f..598c43260 100644 --- a/tests/tests/wgpu-gpu/buffer.rs +++ b/tests/tests/wgpu-gpu/buffer.rs @@ -32,7 +32,7 @@ async fn test_empty_buffer_range(ctx: &TestingContext, buffer_size: u64, label: .unwrap(); { - let view = b0.slice(0..0).get_mapped_range(); + let view = b0.slice(0..0).get_mapped_range().unwrap(); assert!(view.is_empty()); } @@ -88,7 +88,7 @@ async fn test_empty_buffer_range(ctx: &TestingContext, buffer_size: u64, label: }); { - let view = b1.slice(0..0).get_mapped_range_mut(); + let view = b1.slice(0..0).get_mapped_range_mut().unwrap(); assert_eq!(view.len(), 0); } @@ -147,7 +147,7 @@ static MAP_OFFSET: GpuTestConfiguration = GpuTestConfiguration::new() { let slice = write_buf.slice(32..48); - let mut view = slice.get_mapped_range_mut(); + let mut view = slice.get_mapped_range_mut().unwrap(); for byte in view.slice(..) { byte.write(2); } @@ -172,7 +172,7 @@ static MAP_OFFSET: GpuTestConfiguration = GpuTestConfiguration::new() .unwrap(); let slice = read_buf.slice(..); - let view = slice.get_mapped_range(); + let view = slice.get_mapped_range().unwrap(); for byte in &view[0..32] { assert_eq!(*byte, 0); } diff --git a/tests/tests/wgpu-gpu/buffer_usages.rs b/tests/tests/wgpu-gpu/buffer_usages.rs index b0a65583b..f099c207d 100644 --- a/tests/tests/wgpu-gpu/buffer_usages.rs +++ b/tests/tests/wgpu-gpu/buffer_usages.rs @@ -161,7 +161,7 @@ async fn map_test( if !before_unmap && !before_destroy { { - let view = buffer.slice(0..size).get_mapped_range(); + let view = buffer.slice(0..size).get_mapped_range().unwrap(); assert!(!view.is_empty()); } diff --git a/tests/tests/wgpu-gpu/clip_distances.rs b/tests/tests/wgpu-gpu/clip_distances.rs index e0e75275e..a15933cfb 100644 --- a/tests/tests/wgpu-gpu/clip_distances.rs +++ b/tests/tests/wgpu-gpu/clip_distances.rs @@ -137,7 +137,7 @@ async fn clip_distances(ctx: TestingContext) { ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await .unwrap(); - let data: &[u8] = &slice.get_mapped_range(); + let data: &[u8] = &slice.get_mapped_range().unwrap(); // We should have filled the upper sector of the texture. Verify that this is the case. assert_eq!(data[128 + 64 * 256], 0xFF); diff --git a/tests/tests/wgpu-gpu/cloneable_types.rs b/tests/tests/wgpu-gpu/cloneable_types.rs index fd578f6cc..1c9831b6d 100644 --- a/tests/tests/wgpu-gpu/cloneable_types.rs +++ b/tests/tests/wgpu-gpu/cloneable_types.rs @@ -24,6 +24,7 @@ fn cloneable_buffers(ctx: TestingContext) { buffer .slice(..) .get_mapped_range_mut() + .unwrap() .copy_from_slice(&buffer_contents); buffer.unmap(); @@ -35,7 +36,7 @@ fn cloneable_buffers(ctx: TestingContext) { let cloned_buffer_contents = buffer_contents.clone(); buffer.slice(..).map_async(wgpu::MapMode::Read, move |_| { - let data = cloned_buffer.slice(..).get_mapped_range(); + let data = cloned_buffer.slice(..).get_mapped_range().unwrap(); assert_eq!(&*data, &cloned_buffer_contents); }); @@ -44,7 +45,7 @@ fn cloneable_buffers(ctx: TestingContext) { .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); - let data = buffer.slice(..).get_mapped_range(); + let data = buffer.slice(..).get_mapped_range().unwrap(); assert_eq!(&*data, &buffer_contents); } diff --git a/tests/tests/wgpu-gpu/compute_pass_ownership.rs b/tests/tests/wgpu-gpu/compute_pass_ownership.rs index c7d4a5725..4e1330331 100644 --- a/tests/tests/wgpu-gpu/compute_pass_ownership.rs +++ b/tests/tests/wgpu-gpu/compute_pass_ownership.rs @@ -242,7 +242,7 @@ async fn assert_compute_pass_executed_normally( .await .unwrap(); - let data = cpu_buffer.slice(..).get_mapped_range(); + let data = cpu_buffer.slice(..).get_mapped_range().unwrap(); let floats: &[f32] = bytemuck::cast_slice(&data); assert_eq!(floats, [2.0, 4.0, 6.0, 8.0]); diff --git a/tests/tests/wgpu-gpu/dispatch_workgroups_indirect.rs b/tests/tests/wgpu-gpu/dispatch_workgroups_indirect.rs index 23be840cc..ea3539abf 100644 --- a/tests/tests/wgpu-gpu/dispatch_workgroups_indirect.rs +++ b/tests/tests/wgpu-gpu/dispatch_workgroups_indirect.rs @@ -313,7 +313,11 @@ async fn run_test(ctx: &TestingContext, num_workgroups: &[u32; 3]) -> [u32; 3] { .await .unwrap(); - let view = test_resources.readback_buffer.slice(..).get_mapped_range(); + let view = test_resources + .readback_buffer + .slice(..) + .get_mapped_range() + .unwrap(); let current_res = *bytemuck::from_bytes(&view); drop(view); diff --git a/tests/tests/wgpu-gpu/draw_indirect.rs b/tests/tests/wgpu-gpu/draw_indirect.rs index 870d3a8fc..7125fc938 100644 --- a/tests/tests/wgpu-gpu/draw_indirect.rs +++ b/tests/tests/wgpu-gpu/draw_indirect.rs @@ -346,7 +346,7 @@ async fn run_test_inner( .await .unwrap(); - let data = slice.get_mapped_range(); + let data = slice.get_mapped_range().unwrap(); let succeeded = if expect_noop { data.iter().all(|b| *b == 0) } else { @@ -809,7 +809,7 @@ async fn indirect_buffer_offsets(ctx: TestingContext) { .await .unwrap(); - let data = slice.get_mapped_range(); + let data = slice.get_mapped_range().unwrap(); let half = data.len() / 2; let succeeded = data[..half].iter().all(|b| *b == u8::MAX) && data[half..].iter().all(|b| *b == 0); diff --git a/tests/tests/wgpu-gpu/external_image_copy.rs b/tests/tests/wgpu-gpu/external_image_copy.rs index 044e26324..1c6d41aff 100644 --- a/tests/tests/wgpu-gpu/external_image_copy.rs +++ b/tests/tests/wgpu-gpu/external_image_copy.rs @@ -332,7 +332,7 @@ static IMAGE_BITMAP_IMPORT: GpuTestConfiguration = .await .unwrap(); - let buffer = readback_buffer.slice(..).get_mapped_range(); + let buffer = readback_buffer.slice(..).get_mapped_range().unwrap(); // 64 because of 256 byte alignment / 4. let gpu_image = image::RgbaImage::from_vec(64, 3, buffer.to_vec()).unwrap(); diff --git a/tests/tests/wgpu-gpu/external_texture/mod.rs b/tests/tests/wgpu-gpu/external_texture/mod.rs index 7df1cc1d6..a71bac422 100644 --- a/tests/tests/wgpu-gpu/external_texture/mod.rs +++ b/tests/tests/wgpu-gpu/external_texture/mod.rs @@ -227,7 +227,7 @@ fn get_dimensions(ctx: &TestingContext, texture_resource: wgpu::BindingResource) .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); - let data = buffer_slice.get_mapped_range(); + let data = buffer_slice.get_mapped_range().unwrap(); let size: &[u32] = bytemuck::cast_slice(&data); size.try_into().unwrap() } @@ -312,7 +312,7 @@ fn get_loads( .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); - let data = buffer_slice.get_mapped_range(); + let data = buffer_slice.get_mapped_range().unwrap(); let values: &[[f32; 4]] = bytemuck::cast_slice(&data); values.to_vec() } @@ -405,7 +405,7 @@ fn get_samples( .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); - let data = buffer_slice.get_mapped_range(); + let data = buffer_slice.get_mapped_range().unwrap(); let values: &[[f32; 4]] = bytemuck::cast_slice(&data); values.to_vec() } diff --git a/tests/tests/wgpu-gpu/immediates.rs b/tests/tests/wgpu-gpu/immediates.rs index c5e8f8bca..814e099b7 100644 --- a/tests/tests/wgpu-gpu/immediates.rs +++ b/tests/tests/wgpu-gpu/immediates.rs @@ -151,7 +151,7 @@ async fn partial_update_test(ctx: TestingContext) { .await .unwrap(); - let data = cpu_buffer.slice(..).get_mapped_range(); + let data = cpu_buffer.slice(..).get_mapped_range().unwrap(); let floats: &[f32] = bytemuck::cast_slice(&data); @@ -367,7 +367,7 @@ async fn render_pass_test(ctx: &TestingContext, use_render_bundle: bool) { ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await .unwrap(); - let mapped_data = cpu_buffer.slice(..).get_mapped_range(); + let mapped_data = cpu_buffer.slice(..).get_mapped_range().unwrap(); let result = bytemuck::cast_slice::(&mapped_data).to_vec(); drop(mapped_data); cpu_buffer.unmap(); diff --git a/tests/tests/wgpu-gpu/multiview/mod.rs b/tests/tests/wgpu-gpu/multiview/mod.rs index 2f99f81ad..b3927a3eb 100644 --- a/tests/tests/wgpu-gpu/multiview/mod.rs +++ b/tests/tests/wgpu-gpu/multiview/mod.rs @@ -212,7 +212,7 @@ async fn run_test(ctx: TestingContext, layer_mask: u32, sample_count: u32) { .await .unwrap(); - let data = slice.get_mapped_range(); + let data = slice.get_mapped_range().unwrap(); let each_texture_size = (TEXTURE_SIZE * TEXTURE_SIZE) as usize; assert_eq!(data.len(), each_texture_size * num_layers as usize); for view_idx in 0..num_layers as usize { diff --git a/tests/tests/wgpu-gpu/occlusion_query/mod.rs b/tests/tests/wgpu-gpu/occlusion_query/mod.rs index f546f4365..1a888aff4 100644 --- a/tests/tests/wgpu-gpu/occlusion_query/mod.rs +++ b/tests/tests/wgpu-gpu/occlusion_query/mod.rs @@ -129,7 +129,7 @@ static OCCLUSION_QUERY: GpuTestConfiguration = GpuTestConfiguration::new() ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await .unwrap(); - let query_buffer_view = mapping_buffer.slice(..).get_mapped_range(); + let query_buffer_view = mapping_buffer.slice(..).get_mapped_range().unwrap(); let query_data: &[u64; 3] = bytemuck::from_bytes(&query_buffer_view); // WebGPU only defines query results as zero/non-zero diff --git a/tests/tests/wgpu-gpu/oob_indexing.rs b/tests/tests/wgpu-gpu/oob_indexing.rs index aa5e98285..343b91a92 100644 --- a/tests/tests/wgpu-gpu/oob_indexing.rs +++ b/tests/tests/wgpu-gpu/oob_indexing.rs @@ -59,7 +59,11 @@ static RESTRICT_WORKGROUP_PRIVATE_FUNCTION_LET: GpuTestConfiguration = GpuTestCo .await .unwrap(); - let view = test_resources.readback_buffer.slice(..).get_mapped_range(); + let view = test_resources + .readback_buffer + .slice(..) + .get_mapped_range() + .unwrap(); let current_res: [u32; 12] = *bytemuck::from_bytes(&view); drop(view); @@ -462,7 +466,7 @@ async fn d3d12_restrict_dynamic_buffers(ctx: TestingContext) { .await .unwrap(); - let view = readback_buffer.slice(..).get_mapped_range(); + let view = readback_buffer.slice(..).get_mapped_range().unwrap(); let current_res: [u32; 3] = *bytemuck::from_bytes(&view); drop(view); diff --git a/tests/tests/wgpu-gpu/pipeline_cache.rs b/tests/tests/wgpu-gpu/pipeline_cache.rs index 3ac284cab..e409c7a8a 100644 --- a/tests/tests/wgpu-gpu/pipeline_cache.rs +++ b/tests/tests/wgpu-gpu/pipeline_cache.rs @@ -183,7 +183,7 @@ async fn validate_pipeline( .await .unwrap(); - let data = cpu_buffer.slice(..).get_mapped_range(); + let data = cpu_buffer.slice(..).get_mapped_range().unwrap(); let arrays: &[u32] = bytemuck::cast_slice(&data); diff --git a/tests/tests/wgpu-gpu/regression/issue_4122.rs b/tests/tests/wgpu-gpu/regression/issue_4122.rs index 41b0715c4..419b3cd84 100644 --- a/tests/tests/wgpu-gpu/regression/issue_4122.rs +++ b/tests/tests/wgpu-gpu/regression/issue_4122.rs @@ -43,7 +43,7 @@ async fn fill_test(ctx: &TestingContext, range: Range, size: u64) -> bool { .unwrap(); let buffer_slice = cpu_buffer.slice(..); - let buffer_data = buffer_slice.get_mapped_range(); + let buffer_data = buffer_slice.get_mapped_range().unwrap(); let first_clear_byte = buffer_data .iter() diff --git a/tests/tests/wgpu-gpu/regression/issue_6827.rs b/tests/tests/wgpu-gpu/regression/issue_6827.rs index 97ad32be4..fac6ae3fe 100644 --- a/tests/tests/wgpu-gpu/regression/issue_6827.rs +++ b/tests/tests/wgpu-gpu/regression/issue_6827.rs @@ -286,7 +286,7 @@ impl TextureCopyParameters { // by copying it one row at a time. let mut texel_vector: Vec = Vec::new(); { - let mapped: &[u8] = &buffer.slice(..).get_mapped_range(); + let mapped: &[u8] = &buffer.slice(..).get_mapped_range().unwrap(); for row in 0..self.row_count() { let byte_start_of_row = (self.padded_bytes_per_row()) as usize * row; texel_vector.extend(bytemuck::cast_slice::( diff --git a/tests/tests/wgpu-gpu/render_pass_ownership.rs b/tests/tests/wgpu-gpu/render_pass_ownership.rs index da0d3432c..5932b6e0e 100644 --- a/tests/tests/wgpu-gpu/render_pass_ownership.rs +++ b/tests/tests/wgpu-gpu/render_pass_ownership.rs @@ -351,7 +351,7 @@ async fn assert_render_pass_executed_normally( .await .unwrap(); - let data = cpu_buffer.slice(..).get_mapped_range(); + let data = cpu_buffer.slice(..).get_mapped_range().unwrap(); let floats: &[f32] = bytemuck::cast_slice(&data); assert!(floats[0] >= 2.0); diff --git a/tests/tests/wgpu-gpu/render_target.rs b/tests/tests/wgpu-gpu/render_target.rs index 78784b085..7be8ab0c3 100644 --- a/tests/tests/wgpu-gpu/render_target.rs +++ b/tests/tests/wgpu-gpu/render_target.rs @@ -244,7 +244,7 @@ async fn run_test( .await .unwrap(); - let data = slice.get_mapped_range(); + let data = slice.get_mapped_range().unwrap(); let succeeded = data.iter().all(|b| *b == u8::MAX); assert!(succeeded); } @@ -436,7 +436,7 @@ async fn run_test_3d(ctx: TestingContext) { .await .unwrap(); - let data = slice.get_mapped_range(); + let data = slice.get_mapped_range().unwrap(); let succeeded = data.iter().all(|b| *b == u8::MAX); assert!(succeeded); } diff --git a/tests/tests/wgpu-gpu/samplers.rs b/tests/tests/wgpu-gpu/samplers.rs index b05077443..4673e0961 100644 --- a/tests/tests/wgpu-gpu/samplers.rs +++ b/tests/tests/wgpu-gpu/samplers.rs @@ -545,7 +545,7 @@ fn sampler_bind_group(ctx: TestingContext, group_type: GroupType) { .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); - let buffer_data = buffer_slice.get_mapped_range(); + let buffer_data = buffer_slice.get_mapped_range().unwrap(); let f32_buffer: &[f32] = bytemuck::cast_slice(&buffer_data); diff --git a/tests/tests/wgpu-gpu/shader/array_size_overrides.rs b/tests/tests/wgpu-gpu/shader/array_size_overrides.rs index 0e6ea7953..ba6487abf 100644 --- a/tests/tests/wgpu-gpu/shader/array_size_overrides.rs +++ b/tests/tests/wgpu-gpu/shader/array_size_overrides.rs @@ -156,7 +156,7 @@ async fn array_size_overrides( mapping_buffer.slice(..).map_async(MapMode::Read, |_| ()); ctx.async_poll(PollType::wait_indefinitely()).await.unwrap(); - let mapped = mapping_buffer.slice(..).get_mapped_range(); + let mapped = mapping_buffer.slice(..).get_mapped_range().unwrap(); let typed: &[u32] = bytemuck::cast_slice(&mapped); assert_eq!(typed, out); diff --git a/tests/tests/wgpu-gpu/shader/mod.rs b/tests/tests/wgpu-gpu/shader/mod.rs index 41e9fcbc8..89b8d3381 100644 --- a/tests/tests/wgpu-gpu/shader/mod.rs +++ b/tests/tests/wgpu-gpu/shader/mod.rs @@ -376,7 +376,7 @@ async fn shader_input_output_test( mapping_buffer.slice(..).map_async(MapMode::Read, |_| ()); ctx.async_poll(PollType::wait_indefinitely()).await.unwrap(); - let mapped = mapping_buffer.slice(..).get_mapped_range(); + let mapped = mapping_buffer.slice(..).get_mapped_range().unwrap(); let typed: &[u32] = bytemuck::cast_slice(&mapped); diff --git a/tests/tests/wgpu-gpu/shader/workgroup_size_overrides.rs b/tests/tests/wgpu-gpu/shader/workgroup_size_overrides.rs index 3d48ca2a8..8aa622cd5 100644 --- a/tests/tests/wgpu-gpu/shader/workgroup_size_overrides.rs +++ b/tests/tests/wgpu-gpu/shader/workgroup_size_overrides.rs @@ -113,7 +113,7 @@ async fn workgroup_size_overrides( mapping_buffer.slice(..).map_async(MapMode::Read, |_| ()); ctx.async_poll(PollType::wait_indefinitely()).await.unwrap(); - let mapped = mapping_buffer.slice(..).get_mapped_range(); + let mapped = mapping_buffer.slice(..).get_mapped_range().unwrap(); let typed: &[u32] = bytemuck::cast_slice(&mapped); assert_eq!(typed, out); diff --git a/tests/tests/wgpu-gpu/shader/zero_init_workgroup_mem.rs b/tests/tests/wgpu-gpu/shader/zero_init_workgroup_mem.rs index 16c2eb52b..a02099091 100644 --- a/tests/tests/wgpu-gpu/shader/zero_init_workgroup_mem.rs +++ b/tests/tests/wgpu-gpu/shader/zero_init_workgroup_mem.rs @@ -144,7 +144,7 @@ static ZERO_INIT_WORKGROUP_MEMORY: GpuTestConfiguration = GpuTestConfiguration:: mapping_buffer.slice(..).map_async(MapMode::Read, |_| ()); ctx.async_poll(PollType::wait_indefinitely()).await.unwrap(); - let mapped = mapping_buffer.slice(..).get_mapped_range(); + let mapped = mapping_buffer.slice(..).get_mapped_range().unwrap(); let typed: &[u32] = bytemuck::cast_slice(&mapped); diff --git a/tests/tests/wgpu-gpu/shader_view_format/mod.rs b/tests/tests/wgpu-gpu/shader_view_format/mod.rs index 8677d6493..367e16501 100644 --- a/tests/tests/wgpu-gpu/shader_view_format/mod.rs +++ b/tests/tests/wgpu-gpu/shader_view_format/mod.rs @@ -194,7 +194,7 @@ async fn reinterpret( .await .unwrap(); - let data: Vec = slice.get_mapped_range().to_vec(); + let data: Vec = slice.get_mapped_range().unwrap().to_vec(); let tolerance_data: [[u8; 4]; 4] = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1, 1, 1, 0]]; for h in 0..size.height { diff --git a/tests/tests/wgpu-gpu/texture_binding/mod.rs b/tests/tests/wgpu-gpu/texture_binding/mod.rs index 62b16e385..c8ad18a8f 100644 --- a/tests/tests/wgpu-gpu/texture_binding/mod.rs +++ b/tests/tests/wgpu-gpu/texture_binding/mod.rs @@ -184,6 +184,6 @@ fn single_scalar_load(ctx: TestingContext) { ctx.device.poll(PollType::wait_indefinitely()).unwrap(); recv.recv_timeout(Duration::from_secs(10)) .expect("mapping should not take this long"); - let val = *bytemuck::from_bytes::<[f32; 4]>(&buffer.slice(..).get_mapped_range()); + let val = *bytemuck::from_bytes::<[f32; 4]>(&buffer.slice(..).get_mapped_range().unwrap()); assert_eq!(val, [0.0, 0.0, 0.0, 1.0]); } diff --git a/tests/tests/wgpu-gpu/timestamp_normalization/utils.rs b/tests/tests/wgpu-gpu/timestamp_normalization/utils.rs index 754021e29..3ea566dd9 100644 --- a/tests/tests/wgpu-gpu/timestamp_normalization/utils.rs +++ b/tests/tests/wgpu-gpu/timestamp_normalization/utils.rs @@ -286,5 +286,5 @@ fn process_shader(ctx: TestingContext, inputs: &[u8], entry_point_src: &str) -> .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); - pulldown_buffer.get_mapped_range(..).to_vec() + pulldown_buffer.get_mapped_range(..).unwrap().to_vec() } diff --git a/tests/tests/wgpu-gpu/timestamp_query.rs b/tests/tests/wgpu-gpu/timestamp_query.rs index a19bcf2f1..321cca5fd 100644 --- a/tests/tests/wgpu-gpu/timestamp_query.rs +++ b/tests/tests/wgpu-gpu/timestamp_query.rs @@ -124,7 +124,7 @@ fn timestamp_query(ctx: TestingContext) { ctx.device .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); - let query_buffer_view = mapping_buffer.slice(..).get_mapped_range(); + let query_buffer_view = mapping_buffer.slice(..).get_mapped_range().unwrap(); let query_data: &[u64] = bytemuck::cast_slice(&query_buffer_view); for i in 0..ITERATIONS { diff --git a/tests/tests/wgpu-gpu/transient.rs b/tests/tests/wgpu-gpu/transient.rs index a408b342c..6ec3629a1 100644 --- a/tests/tests/wgpu-gpu/transient.rs +++ b/tests/tests/wgpu-gpu/transient.rs @@ -153,7 +153,7 @@ static RESOLVE_WITH_TRANSIENT: GpuTestConfiguration = GpuTestConfiguration::new( .await .unwrap(); - let data = slice.get_mapped_range(); + let data = slice.get_mapped_range().unwrap(); let succeeded = data.iter().all(|b| *b == u8::MAX); assert!(succeeded); }); diff --git a/tests/tests/wgpu-gpu/vertex_formats/mod.rs b/tests/tests/wgpu-gpu/vertex_formats/mod.rs index aaaa2359f..a9b967186 100644 --- a/tests/tests/wgpu-gpu/vertex_formats/mod.rs +++ b/tests/tests/wgpu-gpu/vertex_formats/mod.rs @@ -391,7 +391,7 @@ async fn vertex_formats_common(ctx: TestingContext, tests: &[Test<'_>]) { ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await .unwrap(); - let data: Vec = bytemuck::cast_slice(&slice.get_mapped_range()).to_vec(); + let data: Vec = bytemuck::cast_slice(&slice.get_mapped_range().unwrap()).to_vec(); let case_name = format!("Case {:?}", test.case); diff --git a/tests/tests/wgpu-gpu/vertex_indices/mod.rs b/tests/tests/wgpu-gpu/vertex_indices/mod.rs index 5b48ac3cb..f9c01cecc 100644 --- a/tests/tests/wgpu-gpu/vertex_indices/mod.rs +++ b/tests/tests/wgpu-gpu/vertex_indices/mod.rs @@ -450,7 +450,7 @@ async fn vertex_index_common(ctx: TestingContext) { ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await .unwrap(); - let data: Vec = bytemuck::cast_slice(&slice.get_mapped_range()).to_vec(); + let data: Vec = bytemuck::cast_slice(&slice.get_mapped_range().unwrap()).to_vec(); let case_name = format!( "Case {:?} getting indices from {:?} using {:?} draw calls, encoded with a {:?}", diff --git a/tests/tests/wgpu-gpu/vertex_state.rs b/tests/tests/wgpu-gpu/vertex_state.rs index cb8b45547..e120cf479 100644 --- a/tests/tests/wgpu-gpu/vertex_state.rs +++ b/tests/tests/wgpu-gpu/vertex_state.rs @@ -198,7 +198,7 @@ async fn set_array_stride_to_0(ctx: TestingContext) { .await .unwrap(); - let data = slice.get_mapped_range(); + let data = slice.get_mapped_range().unwrap(); let succeeded = data.iter().all(|b| *b == u8::MAX); assert!(succeeded); } diff --git a/tests/tests/wgpu-gpu/write_texture.rs b/tests/tests/wgpu-gpu/write_texture.rs index 0f19075b4..e177c14fb 100644 --- a/tests/tests/wgpu-gpu/write_texture.rs +++ b/tests/tests/wgpu-gpu/write_texture.rs @@ -97,7 +97,7 @@ static WRITE_TEXTURE_SUBSET_2D: GpuTestConfiguration = ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await .unwrap(); - let data: Vec = slice.get_mapped_range().to_vec(); + let data: Vec = slice.get_mapped_range().unwrap().to_vec(); for byte in &data[..(size as usize * 2)] { assert_eq!(*byte, 1); @@ -192,7 +192,7 @@ static WRITE_TEXTURE_SUBSET_3D: GpuTestConfiguration = ctx.async_poll(wgpu::PollType::wait_indefinitely()) .await .unwrap(); - let data: Vec = slice.get_mapped_range().to_vec(); + let data: Vec = slice.get_mapped_range().unwrap().to_vec(); for byte in &data[..((size * size) as usize * 2)] { assert_eq!(*byte, 1); @@ -338,7 +338,7 @@ static WRITE_TEXTURE_VIA_STAGING_BUFFER: GpuTestConfiguration = GpuTestConfigura let slice = read_buffer.slice(..); slice.map_async(MapMode::Read, |_| ()); ctx.async_poll(PollType::wait_indefinitely()).await.unwrap(); - let read_data: Vec = slice.get_mapped_range().to_vec(); + let read_data: Vec = slice.get_mapped_range().unwrap().to_vec(); for x in 0..write_width { for y in 0..write_height { diff --git a/tests/tests/wgpu-validation/api/buffer_mapping.rs b/tests/tests/wgpu-validation/api/buffer_mapping.rs index 09e316377..4e83963bd 100644 --- a/tests/tests/wgpu-validation/api/buffer_mapping.rs +++ b/tests/tests/wgpu-validation/api/buffer_mapping.rs @@ -38,7 +38,7 @@ fn full_immutable_binding() { buffer.map_async(wgpu::MapMode::Read, .., |_| {}); device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); - let mapping = buffer.slice(..).get_mapped_range(); + let mapping = buffer.slice(..).get_mapped_range().unwrap(); read_mapping_is_zeroed(&mapping); @@ -59,7 +59,7 @@ fn full_mut_binding() { mapped_at_creation: true, }); - let mut mapping = buffer.slice(..).get_mapped_range_mut(); + let mut mapping = buffer.slice(..).get_mapped_range_mut().unwrap(); write_mapping_is_zeroed(mapping.slice(..)); @@ -83,8 +83,8 @@ fn split_immutable_binding() { buffer.map_async(wgpu::MapMode::Read, .., |_| {}); device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); - let mapping0 = buffer.slice(0..512).get_mapped_range(); - let mapping1 = buffer.slice(512..1024).get_mapped_range(); + let mapping0 = buffer.slice(0..512).get_mapped_range().unwrap(); + let mapping1 = buffer.slice(512..1024).get_mapped_range().unwrap(); read_mapping_is_zeroed(&mapping0); read_mapping_is_zeroed(&mapping1); @@ -107,8 +107,8 @@ fn split_mut_binding() { mapped_at_creation: true, }); - let mut mapping0 = buffer.slice(0..512).get_mapped_range_mut(); - let mut mapping1 = buffer.slice(512..1024).get_mapped_range_mut(); + let mut mapping0 = buffer.slice(0..512).get_mapped_range_mut().unwrap(); + let mut mapping1 = buffer.slice(512..1024).get_mapped_range_mut().unwrap(); write_mapping_is_zeroed(mapping0.slice(..)); write_mapping_is_zeroed(mapping1.slice(..)); @@ -131,13 +131,12 @@ fn overlapping_ref_binding() { mapped_at_creation: true, }); - let _mapping0 = buffer.slice(0..512).get_mapped_range(); - let _mapping1 = buffer.slice(256..768).get_mapped_range(); + let _mapping0 = buffer.slice(0..512).get_mapped_range().unwrap(); + let _mapping1 = buffer.slice(256..768).get_mapped_range().unwrap(); } -/// Ensure that two overlapping mutably mapped ranges panics. +/// Ensure that two overlapping mutably mapped ranges returns an error. #[test] -#[should_panic(expected = "break Rust memory aliasing rules")] fn overlapping_mut_binding() { let (device, _queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default()); @@ -148,14 +147,13 @@ fn overlapping_mut_binding() { mapped_at_creation: true, }); - let _mapping0 = buffer.slice(0..512).get_mapped_range_mut(); - let _mapping1 = buffer.slice(256..768).get_mapped_range_mut(); + let _mapping0 = buffer.slice(0..512).get_mapped_range_mut().unwrap(); + let result = buffer.slice(256..768).get_mapped_range_mut(); + assert!(result.is_err()); } -/// Ensure that when you try to get a mapped range from an unmapped buffer, it panics with -/// an error mentioning a completely unmapped buffer. +/// Ensure that getting a mapped range from an unmapped buffer returns an error. #[test] -#[should_panic(expected = "an unmapped buffer")] fn not_mapped() { let (device, _queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default()); @@ -166,15 +164,12 @@ fn not_mapped() { mapped_at_creation: false, }); - let _mapping = buffer.slice(..).get_mapped_range_mut(); + let result = buffer.slice(..).get_mapped_range_mut(); + assert!(result.is_err()); } -/// Ensure that when you partially map a buffer, then try to read outside of that range, it panics -/// mentioning the mapped indices. +/// Ensure that getting a mapped range outside the mapped region returns an error. #[test] -#[should_panic( - expected = "Attempted to get range 512..1024 (Mutable), but the mapped range is 0..512" -)] fn partially_mapped() { let (device, _queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default()); @@ -188,8 +183,9 @@ fn partially_mapped() { buffer.map_async(wgpu::MapMode::Write, 0..512, |_| {}); device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); - let _mapping0 = buffer.slice(0..512).get_mapped_range_mut(); - let _mapping1 = buffer.slice(512..1024).get_mapped_range_mut(); + let _mapping0 = buffer.slice(0..512).get_mapped_range_mut().unwrap(); + let result = buffer.slice(512..1024).get_mapped_range_mut(); + assert!(result.is_err()); } /// Ensure that you cannot unmap a buffer while there are still accessible mapped views. @@ -205,6 +201,6 @@ fn unmap_while_visible() { mapped_at_creation: true, }); - let _mapping0 = buffer.slice(..).get_mapped_range_mut(); + let _mapping0 = buffer.slice(..).get_mapped_range_mut().unwrap(); buffer.unmap(); } diff --git a/wgpu/src/api/buffer.rs b/wgpu/src/api/buffer.rs index 5e013263f..786ba77ac 100644 --- a/wgpu/src/api/buffer.rs +++ b/wgpu/src/api/buffer.rs @@ -1,4 +1,4 @@ -use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; use core::{ error, fmt, ops::{Bound, Deref, Range, RangeBounds}, @@ -139,7 +139,7 @@ use crate::*; /// let capturable = buffer.clone(); /// buffer.map_async(wgpu::MapMode::Write, .., move |result| { /// if result.is_ok() { -/// let mut view = capturable.get_mapped_range_mut(..); +/// let mut view = capturable.get_mapped_range_mut(..).unwrap(); /// let mut floats: wgpu::WriteOnly<[[u8; 4]]> = view.slice(..).into_chunks::<4>().0; /// floats.fill(42.0f32.to_ne_bytes()); /// drop(view); @@ -406,7 +406,7 @@ impl Buffer { /// /// This can also be performed using [`BufferSlice::get_mapped_range()`]. /// - /// # Panics + /// # Errors /// /// - If `bounds` is outside of the bounds of `self`. /// - If `bounds` does not start at a multiple of [`MAP_ALIGNMENT`]. @@ -416,7 +416,10 @@ impl Buffer { /// /// [mapped]: Buffer#mapping-buffers #[track_caller] - pub fn get_mapped_range>(&self, bounds: S) -> BufferView { + pub fn get_mapped_range>( + &self, + bounds: S, + ) -> Result { self.slice(bounds).get_mapped_range() } @@ -430,7 +433,7 @@ impl Buffer { /// /// This can also be performed using [`BufferSlice::get_mapped_range_mut()`]. /// - /// # Panics + /// # Errors /// /// - If `bounds` is outside of the bounds of `self`. /// - If `bounds` does not start at a multiple of [`MAP_ALIGNMENT`]. @@ -440,7 +443,10 @@ impl Buffer { /// /// [mapped]: Buffer#mapping-buffers #[track_caller] - pub fn get_mapped_range_mut>(&self, bounds: S) -> BufferViewMut { + pub fn get_mapped_range_mut>( + &self, + bounds: S, + ) -> Result { self.slice(bounds).get_mapped_range_mut() } @@ -589,7 +595,7 @@ impl<'a> BufferSlice<'a> { /// /// This can also be performed using [`Buffer::get_mapped_range()`]. /// - /// # Panics + /// # Errors /// /// - 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. @@ -598,19 +604,16 @@ impl<'a> BufferSlice<'a> { /// /// [mapped]: Buffer#mapping-buffers #[track_caller] - pub fn get_mapped_range(&self) -> BufferView { + pub fn get_mapped_range(&self) -> Result { let subrange = Subrange::new(self.offset, self.size, RangeMappingKind::Immutable); - self.buffer - .map_context - .lock() - .validate_and_add(subrange.clone()); - let range = self.buffer.inner.get_mapped_range(subrange.index); - BufferView { + let range = self.buffer.inner.get_mapped_range(subrange.index.clone())?; + self.buffer.map_context.lock().validate_and_add(subrange)?; + Ok(BufferView { buffer: self.buffer.clone(), size: self.size, offset: self.offset, inner: range, - } + }) } /// Gain write-only access to the bytes of a [mapped] [`Buffer`]. @@ -623,7 +626,7 @@ impl<'a> BufferSlice<'a> { /// /// This can also be performed using [`Buffer::get_mapped_range_mut()`]. /// - /// # Panics + /// # Errors /// /// - 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. @@ -632,19 +635,16 @@ impl<'a> BufferSlice<'a> { /// /// [mapped]: Buffer#mapping-buffers #[track_caller] - pub fn get_mapped_range_mut(&self) -> BufferViewMut { + pub fn get_mapped_range_mut(&self) -> Result { let subrange = Subrange::new(self.offset, self.size, RangeMappingKind::Mutable); - self.buffer - .map_context - .lock() - .validate_and_add(subrange.clone()); - let range = self.buffer.inner.get_mapped_range(subrange.index); - BufferViewMut { + let range = self.buffer.inner.get_mapped_range(subrange.index.clone())?; + self.buffer.map_context.lock().validate_and_add(subrange)?; + Ok(BufferViewMut { buffer: self.buffer.clone(), size: self.size, offset: self.offset, inner: range, - } + }) } /// Returns the buffer this is a slice of. @@ -785,22 +785,24 @@ impl MapContext { /// Record that the `size` bytes of the buffer at `offset` are now viewed. /// - /// # Panics + /// # Errors /// - /// This panics if the given range is invalid. - #[track_caller] - fn validate_and_add(&mut self, new_sub: Subrange) { + /// 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() { - panic!("tried to call get_mapped_range(_mut) on an unmapped buffer"); + return Err(MapRangeError( + "tried to call get_mapped_range(_mut) on an unmapped buffer".into(), + )); } if !range_contains(&self.mapped_range, &new_sub.index) { - panic!( + 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 - ); + new_sub, + self.mapped_range.start, + self.mapped_range.end + ))); } - // This check is essential for avoiding undefined behavior: it is the // only thing that ensures that `&mut` references to the buffer's // contents don't alias anything else. @@ -808,15 +810,17 @@ impl MapContext { if range_overlaps(&sub.index, &new_sub.index) && !sub.kind.allowed_concurrently_with(new_sub.kind) { - panic!( + return Err(MapRangeError(alloc::format!( "tried to call get_mapped_range(_mut) on a range that has already \ been mapped and would break Rust memory aliasing rules. Attempted \ to get range {}, and the conflicting range is {}", - new_sub, sub - ); + new_sub, + sub + ))); } } self.sub_ranges.push(new_sub); + Ok(()) } /// Record that the `size` bytes of the buffer at `offset` are no longer viewed. @@ -859,6 +863,23 @@ impl fmt::Display for BufferAsyncError { impl error::Error for BufferAsyncError {} +/// Error returned by [`BufferSlice::get_mapped_range`] and [`BufferSlice::get_mapped_range_mut`]. +/// +/// Corresponds to the `OperationError` thrown by +/// [`getMappedRange()`](https://gpuweb.github.io/gpuweb/#dom-gpubuffer-getmappedrange) +/// in the WebGPU spec. +#[derive(Clone, Debug)] +pub struct MapRangeError(pub(crate) String); +static_assertions::assert_impl_all!(MapRangeError: Send, Sync); + +impl fmt::Display for MapRangeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Buffer view error: {}", self.0) + } +} + +impl error::Error for MapRangeError {} + /// Type of buffer mapping. #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum MapMode { diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index a7229b057..c2b37dfb8 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -1288,22 +1288,28 @@ impl WebBuffer { } /// Obtains a reference to the re-usable buffer mapping as a Javascript array view. - fn get_mapped_range(&self, sub_range: Range) -> js_sys::Uint8Array { + fn get_mapped_range( + &self, + sub_range: Range, + ) -> Result { let mut mapping = self.mapping.borrow_mut(); let range = mapping.range.clone(); - let array_buffer = mapping.mapped_buffer.get_or_insert_with(|| { - self.inner + if mapping.mapped_buffer.is_none() { + let buffer = self + .inner .get_mapped_range_with_f64_and_f64( range.start as f64, (range.end - range.start) as f64, ) - .unwrap() - }); - js_sys::Uint8Array::new_with_byte_offset_and_length( + .map_err(|e| crate::MapRangeError(format!("{e:?}")))?; + mapping.mapped_buffer = Some(buffer); + } + let array_buffer = mapping.mapped_buffer.as_ref().unwrap(); + Ok(js_sys::Uint8Array::new_with_byte_offset_and_length( array_buffer, (sub_range.start - range.start) as u32, (sub_range.end - sub_range.start) as u32, - ) + )) } /// Sets the range of the buffer which is presently mapped. @@ -2821,15 +2827,15 @@ impl dispatch::BufferInterface for WebBuffer { fn get_mapped_range( &self, sub_range: Range, - ) -> dispatch::DispatchBufferMappedRange { - let actual_mapping = self.get_mapped_range(sub_range); - WebBufferMappedRange { + ) -> Result { + let actual_mapping = self.get_mapped_range(sub_range)?; + Ok(WebBufferMappedRange { actual_mapping, temporary_mapping: OnceCell::new(), temporary_mapping_modified: false, ident: crate::cmp::Identifier::create(), } - .into() + .into()) } fn unmap(&self) { diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index 7228893ea..3efe1a5fa 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -2246,22 +2246,19 @@ impl dispatch::BufferInterface for CoreBuffer { fn get_mapped_range( &self, sub_range: Range, - ) -> dispatch::DispatchBufferMappedRange { + ) -> Result { let size = sub_range.end - sub_range.start; - match self - .context + self.context .0 .buffer_get_mapped_range(self.id, sub_range.start, Some(size)) - { - Ok((ptr, size)) => CoreBufferMappedRange { - ptr, - size: size as usize, - } - .into(), - Err(err) => self - .context - .handle_error_fatal(err, "Buffer::get_mapped_range"), - } + .map(|(ptr, size)| { + CoreBufferMappedRange { + ptr, + size: size as usize, + } + .into() + }) + .map_err(|err| crate::MapRangeError(self.context.format_error(&err))) } fn unmap(&self) { diff --git a/wgpu/src/dispatch.rs b/wgpu/src/dispatch.rs index d2b2366ed..c497585a8 100644 --- a/wgpu/src/dispatch.rs +++ b/wgpu/src/dispatch.rs @@ -277,8 +277,10 @@ pub trait BufferInterface: CommonTraits { range: Range, callback: BufferMapCallback, ); - fn get_mapped_range(&self, sub_range: Range) - -> DispatchBufferMappedRange; + fn get_mapped_range( + &self, + sub_range: Range, + ) -> Result; fn unmap(&self); diff --git a/wgpu/src/util/belt.rs b/wgpu/src/util/belt.rs index 29093e270..f8b03a23f 100644 --- a/wgpu/src/util/belt.rs +++ b/wgpu/src/util/belt.rs @@ -155,7 +155,9 @@ impl StagingBelt { offset, size.get(), ); - slice_of_belt.get_mapped_range_mut() + slice_of_belt + .get_mapped_range_mut() + .expect("Failed to get mapped range for staging belt buffer") } /// Allocate a staging belt slice with the given `size` and `alignment` and return it. diff --git a/wgpu/src/util/device.rs b/wgpu/src/util/device.rs index 540607b81..adbf6d440 100644 --- a/wgpu/src/util/device.rs +++ b/wgpu/src/util/device.rs @@ -69,6 +69,7 @@ impl DeviceExt for crate::Device { buffer .get_mapped_range_mut(..) + .expect("Failed to get mapped range for buffer created with mapped_at_creation") .slice(..unpadded_size as usize) .copy_from_slice(descriptor.contents); buffer.unmap(); diff --git a/wgpu/src/util/mod.rs b/wgpu/src/util/mod.rs index 06658caa9..8e3d832bf 100644 --- a/wgpu/src/util/mod.rs +++ b/wgpu/src/util/mod.rs @@ -72,7 +72,14 @@ impl DownloadBuffer { return; } - let mapped_range = download.inner.get_mapped_range(0..size); + let mapped_range = match download.inner.get_mapped_range(0..size) { + Ok(range) => range, + Err(e) => { + callback(Err(super::BufferAsyncError)); + log::error!("Failed to get mapped range: {e}"); + return; + } + }; callback(Ok(Self { _gpu_buffer: download, mapped_range,