Wgpu-rs: Add user-friendly buffer type casting support?

Created on 5 Mar 2020  路  2Comments  路  Source: gfx-rs/wgpu-rs

Currently, the buffers returned by Buffer::map_read and Buffer::map_write return types which can be safely converted to &[u8]. If a buffer contains a more complex struct, you either have to cast unsafely or build it manually.

If the BufferReadMapping and BufferWriteMapping structs had an type parameter (it could even be set to u8 by default for backwards compatibility) that was bounded on zerocopy::FromBytes or bytemuck::Pod, it'd be more convenient to safely cast the slice to a slice of an arbitrary type.

For example, BufferReadMapping could be implemented as:

pub struct BufferReadMapping<T> {
    data: *const u8,
    size: usize,
    buffer_id: wgc::id::BufferId,
    _marker: PhantomData<T>,
}
//TODO: proper error type
pub type BufferMapReadResult<T> = Result<BufferReadMapping<T>, ()>;

impl<T: bytemuck::Pod> BufferReadMapping<T>
{
    pub fn as_slice(&self) -> &[T] {
        bytemuck::cast_slice(unsafe {
            slice::from_raw_parts(self.data, self.size)
        })
    }
}

impl<T> Drop for BufferReadMapping<T> {
    fn drop(&mut self) {
        wgn::wgpu_buffer_unmap(self.buffer_id);
    }
}

This would work if BufferReadMapping implemented Deref as well, which might be even more user-friendly.

question

Most helpful comment

Ah, okay, that makes sense. That thread is pretty dense, but the outcome is clear haha.

I would like to see this general problem of matching up data-types between the cpu and gpu sides revisited at some point, but it looks like it's not too important right now.

All 2 comments

FWIW we did have a zeropcopy bound previously but the safety is still questionable because being POD isn't enough (some level still needs to be aware of repr and alignment of fields compared to their representation in shaders, etc.). There's some good discussion in https://github.com/gfx-rs/wgpu-rs/pull/119.

So for now we decided to expose &[u8] and let the caller decide whether the cast is actually safe

Ah, okay, that makes sense. That thread is pretty dense, but the outcome is clear haha.

I would like to see this general problem of matching up data-types between the cpu and gpu sides revisited at some point, but it looks like it's not too important right now.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

donpdonp picture donpdonp  路  3Comments

roman-holovin picture roman-holovin  路  4Comments

yutannihilation picture yutannihilation  路  4Comments

Lokathor picture Lokathor  路  3Comments

m4b picture m4b  路  5Comments