On Mon, Jun 09, 2025 at 05:44:19PM +0200, Paolo Bonzini wrote:
> Date: Mon,  9 Jun 2025 17:44:19 +0200
> From: Paolo Bonzini <pbonz...@redhat.com>
> Subject: [PATCH 1/5] rust: qemu_api: introduce MaybeUninit field projection
> X-Mailer: git-send-email 2.49.0
> 
> Add a macro that makes it possible to convert a MaybeUninit<> into
> another MaybeUninit<> for a single field within it.  Furthermore, it is
> possible to use the resulting MaybeUninitField<> in APIs that take the
> parent object, such as memory_region_init_io().
> 
> This allows removing some of the undefined behavior from instance_init()
> functions, though this may not be the definitive implementation.
> 
> Signed-off-by: Paolo Bonzini <pbonz...@redhat.com>
> ---
>  rust/qemu-api/meson.build   |  1 +
>  rust/qemu-api/src/lib.rs    |  1 +
>  rust/qemu-api/src/uninit.rs | 85 +++++++++++++++++++++++++++++++++++++
>  3 files changed, 87 insertions(+)
>  create mode 100644 rust/qemu-api/src/uninit.rs

...

> +impl<'a, T, U> Deref for MaybeUninitField<'a, T, U> {
> +    type Target = MaybeUninit<U>;
> +
> +    fn deref(&self) -> &MaybeUninit<U> {
> +        // SAFETY: self.child was obtained by dereferencing a valid mutable
> +        // reference; the content of the memory may be invalid or 
> uninitialized
> +        // but MaybeUninit<_> makes no assumption on it
> +        unsafe { &*(self.child.cast()) }
> +    }
> +}
> +
> +impl<'a, T, U> DerefMut for MaybeUninitField<'a, T, U> {
> +    fn deref_mut(&mut self) -> &mut MaybeUninit<U> {
> +        // SAFETY: self.child was obtained by dereferencing a valid mutable
> +        // reference; the content of the memory may be invalid or 
> uninitialized
> +        // but MaybeUninit<_> makes no assumption on it
> +        unsafe { &mut *(self.child.cast()) }
> +    }
> +}

Nice trick.

Reviewed-by: Zhao Liu <zhao1....@intel.com>


Reply via email to