Skip to content
This repository was archived by the owner on Jun 18, 2021. It is now read-only.
This repository was archived by the owner on Jun 18, 2021. It is now read-only.

Add user-friendly buffer type casting support? #190

@lachlansneff

Description

@lachlansneff

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions