wgpu icon indicating copy to clipboard operation
wgpu copied to clipboard

Examples shouldn't use bytemuck to cast out of a get_mapped_range() BufferView

Open Oberdiah opened this issue 1 year ago • 5 comments

Description Currently, the examples use bytemuck::cast_slice() to cast u8 slices returned in the BufferView from get_mapped_range() to slices of larger types (u64s, u32s etc.), but this call panics if the underlying slice is not aligned to the larger type.

https://github.com/gfx-rs/wgpu/blob/26398ea0db98f28c5d129a26f6c5e88442747628/examples/src/timestamp_queries/mod.rs#L169 https://github.com/gfx-rs/wgpu/blob/26398ea0db98f28c5d129a26f6c5e88442747628/examples/src/repeated_compute/mod.rs#L123

At present, wgpu makes no guarantees about the alignment of get_mapped_range(), and in certain situations does in fact return a slice that is not u64-aligned.

Until wgpu can guarantee alignment here, it would be nice to remove this footgun from the examples, as currently code that works there can mysteriously break when put into a larger project.

Additional Information I had previously been using bytemuck::cast_slice() without issue in 0.18.x but upon updating to 22.x the alignment shifted. It only seems to have happened on the Vulkan backend.

Oberdiah avatar Sep 01 '24 21:09 Oberdiah

Just curious as an onlooker: what would be the correct thing to do here?

BGR360 avatar Sep 03 '24 16:09 BGR360

only deal with raw bytes and do memcopies as needed

Wumpf avatar Sep 08 '24 15:09 Wumpf

We should be guarenteing 16byte alignment - this is something webgpu-native discussed at length previously. I think there's another issue about it too.

cwfitzgerald avatar Sep 08 '24 19:09 cwfitzgerald

This one? https://github.com/webgpu-native/webgpu-headers/issues/180

I agree, but until there's any movement there, our examples are wrong as-is

Wumpf avatar Sep 08 '24 19:09 Wumpf

We can use pod_collect_to_vec

cwfitzgerald avatar Dec 02 '25 19:12 cwfitzgerald