Make get_mapped_range return a Result rather than panicking (#9281)

This commit is contained in:
atlv authored and GitHub committed 2026-04-08 21:22:00 -04:00
1 parent daced7acb9
commit ed4a28aef0
57 files changed
+195 -149

No files matched your search

+1
View File
@@ -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
@@ -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<f32> = bytemuck::allocation::pod_collect_to_vec(&mapped);
data.extend_from_slice(&chunk);
drop(mapped);
@@ -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<f32> = if use_f16 {
+1 -1
View File
@@ -744,7 +744,7 @@ impl<E: Example + wgpu::WasmNotSendSync> From<ExampleTestParams<E>>
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),
@@ -185,7 +185,7 @@ async fn get_data<T: bytemuck::Pod>(
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
receiver.recv_async().await.unwrap().unwrap();
let data: Vec<T> =
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();
}
@@ -174,7 +174,7 @@ async fn get_data<T: bytemuck::Pod>(
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
receiver.recv_async().await.unwrap().unwrap();
let data: Vec<T> =
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();
}
+4 -2
View File
@@ -417,11 +417,13 @@ impl crate::framework::Example for Example {
let timestamp_view = query_sets
.mapping_buffer
.slice(..size_of::<TimestampQueries>() 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(&timestamp_view);
let pipeline_stats_data: &PipelineStatisticsQueries =
@@ -137,7 +137,7 @@ async fn run(_path: Option<String>) {
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.");
@@ -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<u32> = bytemuck::allocation::pod_collect_to_vec(&view);
local_buffer.copy_from_slice(&data);
}
+1 -1
View File
@@ -146,7 +146,7 @@ async fn run(_path: Option<String>) {
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.");
@@ -181,7 +181,8 @@ impl Queries {
let timestamp_view = self
.destination_buffer
.slice(..(size_of::<u64>() as wgpu::BufferAddress * self.num_queries))
.get_mapped_range();
.get_mapped_range()
.unwrap();
bytemuck::allocation::pod_collect_to_vec(&timestamp_view)
};
@@ -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<f32> = bytemuck::allocation::pod_collect_to_vec(&data);
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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()
);
});
@@ -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);
}
@@ -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[..]);
}
+4 -4
View File
@@ -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);
}
+1 -1
View File
@@ -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());
}
+1 -1
View File
@@ -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);
+3 -2
View File
@@ -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);
}
@@ -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]);
@@ -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);
+2 -2
View File
@@ -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);
+1 -1
View File
@@ -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();
+3 -3
View File
@@ -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()
}
+2 -2
View File
@@ -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::<u8, i32>(&mapped_data).to_vec();
drop(mapped_data);
cpu_buffer.unmap();
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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
+6 -2
View File
@@ -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);
+1 -1
View File
@@ -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);
@@ -43,7 +43,7 @@ async fn fill_test(ctx: &TestingContext, range: Range<u64>, 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()
@@ -286,7 +286,7 @@ impl TextureCopyParameters {
// by copying it one row at a time.
let mut texel_vector: Vec<C> = 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::<u8, C>(
@@ -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);
+2 -2
View File
@@ -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);
}
+1 -1
View File
@@ -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);
@@ -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);
+1 -1
View File
@@ -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);
@@ -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);
@@ -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);
@@ -194,7 +194,7 @@ async fn reinterpret(
.await
.unwrap();
let data: Vec<u8> = slice.get_mapped_range().to_vec();
let data: Vec<u8> = 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 {
+1 -1
View File
@@ -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]);
}
@@ -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()
}
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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);
});
+1 -1
View File
@@ -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<f32> = bytemuck::cast_slice(&slice.get_mapped_range()).to_vec();
let data: Vec<f32> = bytemuck::cast_slice(&slice.get_mapped_range().unwrap()).to_vec();
let case_name = format!("Case {:?}", test.case);
+1 -1
View File
@@ -450,7 +450,7 @@ async fn vertex_index_common(ctx: TestingContext) {
ctx.async_poll(wgpu::PollType::wait_indefinitely())
.await
.unwrap();
let data: Vec<u32> = bytemuck::cast_slice(&slice.get_mapped_range()).to_vec();
let data: Vec<u32> = bytemuck::cast_slice(&slice.get_mapped_range().unwrap()).to_vec();
let case_name = format!(
"Case {:?} getting indices from {:?} using {:?} draw calls, encoded with a {:?}",
+1 -1
View File
@@ -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);
}
+3 -3
View File
@@ -97,7 +97,7 @@ static WRITE_TEXTURE_SUBSET_2D: GpuTestConfiguration =
ctx.async_poll(wgpu::PollType::wait_indefinitely())
.await
.unwrap();
let data: Vec<u8> = slice.get_mapped_range().to_vec();
let data: Vec<u8> = 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<u8> = slice.get_mapped_range().to_vec();
let data: Vec<u8> = 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<u8> = slice.get_mapped_range().to_vec();
let read_data: Vec<u8> = slice.get_mapped_range().unwrap().to_vec();
for x in 0..write_width {
for y in 0..write_height {
@@ -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();
}
+57 -36
View File
@@ -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<S: RangeBounds<BufferAddress>>(&self, bounds: S) -> BufferView {
pub fn get_mapped_range<S: RangeBounds<BufferAddress>>(
&self,
bounds: S,
) -> Result<BufferView, MapRangeError> {
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<S: RangeBounds<BufferAddress>>(&self, bounds: S) -> BufferViewMut {
pub fn get_mapped_range_mut<S: RangeBounds<BufferAddress>>(
&self,
bounds: S,
) -> Result<BufferViewMut, MapRangeError> {
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<BufferView, MapRangeError> {
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<BufferViewMut, MapRangeError> {
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 {
+17 -11
View File
@@ -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<wgt::BufferAddress>) -> js_sys::Uint8Array {
fn get_mapped_range(
&self,
sub_range: Range<wgt::BufferAddress>,
) -> Result<js_sys::Uint8Array, crate::MapRangeError> {
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<crate::BufferAddress>,
) -> dispatch::DispatchBufferMappedRange {
let actual_mapping = self.get_mapped_range(sub_range);
WebBufferMappedRange {
) -> Result<dispatch::DispatchBufferMappedRange, crate::MapRangeError> {
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) {
+10 -13
View File
@@ -2246,22 +2246,19 @@ impl dispatch::BufferInterface for CoreBuffer {
fn get_mapped_range(
&self,
sub_range: Range<crate::BufferAddress>,
) -> dispatch::DispatchBufferMappedRange {
) -> Result<dispatch::DispatchBufferMappedRange, crate::MapRangeError> {
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) {
+4 -2
View File
@@ -277,8 +277,10 @@ pub trait BufferInterface: CommonTraits {
range: Range<crate::BufferAddress>,
callback: BufferMapCallback,
);
fn get_mapped_range(&self, sub_range: Range<crate::BufferAddress>)
-> DispatchBufferMappedRange;
fn get_mapped_range(
&self,
sub_range: Range<crate::BufferAddress>,
) -> Result<DispatchBufferMappedRange, crate::MapRangeError>;
fn unmap(&self);
+3 -1
View File
@@ -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.
+1
View File
@@ -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();
+8 -1
View File
@@ -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,