From f50aa972fe43e660ce8cc43c3ead16d2a7aaa123 Mon Sep 17 00:00:00 2001 From: sagudev <16504129+sagudev@users.noreply.github.com> Date: Mon, 31 Aug 2026 16:07:44 +0200 Subject: [PATCH] `Buffer::{as, from}_core` Signed-off-by: sagudev <16504129+sagudev@users.noreply.github.com> --- wgpu/src/api/buffer.rs | 35 +++++++++++++++++++++++++++++++++++ wgpu/src/backend/wgpu_core.rs | 10 ++++++++++ 2 files changed, 45 insertions(+) diff --git a/wgpu/src/api/buffer.rs b/wgpu/src/api/buffer.rs index 4bb75ab3a..80cbb64ca 100644 --- a/wgpu/src/api/buffer.rs +++ b/wgpu/src/api/buffer.rs @@ -464,6 +464,41 @@ impl Buffer { } } +#[cfg(wgpu_core)] +impl Buffer { + /// Create a new buffer of wgpu from a wgpu-core buffer. + /// + /// # Arguments + /// + /// - `core_buffer` - wgpu-core buffer. + /// + /// # Safety + /// + /// The caller must ensure that the current state of the wgpu-core buffer is compatible with the provided `mapped_range`. + /// Changes to the wgpu-core buffer's state after this call may lead to undefined behavior if they are not compatible with the provided `mapped_range`. + pub unsafe fn from_core( + core_buffer: alloc::sync::Arc, + mapped_range: Option>, + ) -> Self { + Self { + inner: crate::backend::wgpu_core::CoreBuffer::from_core(core_buffer).into(), + map_context: Arc::new(Mutex::new(MapContext::new(mapped_range))), + } + } + + /// Returns the underlying wgpu-core buffer if this `Buffer` is on the wgpu-core backend, otherwise `None`. + /// + /// # Safety + /// + /// Returning the underlying wgpu-core buffer allows for direct manipulation of the buffer's state, + /// which can lead to undefined behavior if not done carefully. + /// The caller must ensure that any operations performed on the returned buffer are compatible with the current state of the `Buffer` and its mapping context + /// or not use this buffer after calling this function. + pub unsafe fn as_core(&self) -> Option> { + self.inner.as_core_opt().map(|cd| cd.as_core()) + } +} + /// A slice of a [`Buffer`], to be mapped, used for vertex or index data, or the like. /// /// You can create a `BufferSlice` by calling [`Buffer::slice`]: diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index 9d54d07eb..00bbb85a8 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -298,6 +298,16 @@ impl CoreBuffer { pub unsafe fn as_hal(&self) -> Option> { unsafe { self.wgpu_buffer.clone().as_hal::() } } + + pub(crate) fn from_core(core_buffer: Arc) -> Self { + Self { + wgpu_buffer: core_buffer, + } + } + + pub(crate) fn as_core(&self) -> Arc { + self.wgpu_buffer.clone() + } } #[derive(Debug, Clone)]