mirror of
https://github.com/Motorhead1991/qemu.git
synced 2025-07-27 12:23:53 -06:00
rust: provide safe wrapper for MaybeUninit::zeroed()
MaybeUninit::zeroed() is handy, but it introduces unsafe (and has a pretty heavy syntax in general). Introduce a trait that provides the same functionality while staying within safe Rust. In addition, MaybeUninit::zeroed() is not available as a "const" function until Rust 1.75.0, so this also prepares for having handwritten implementations of the trait until we can assume that version. Reviewed-by: Junjie Mao <junjie.mao@hotmail.com> Reviewed-by: Kevin Wolf <kwolf@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
This commit is contained in:
parent
c92c447ff0
commit
6e50bde1e1
6 changed files with 35 additions and 10 deletions
23
rust/qemu-api/src/zeroable.rs
Normal file
23
rust/qemu-api/src/zeroable.rs
Normal file
|
@ -0,0 +1,23 @@
|
|||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
/// Encapsulates the requirement that
|
||||
/// `MaybeUninit::<Self>::zeroed().assume_init()` does not cause
|
||||
/// undefined behavior.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Do not add this trait to a type unless all-zeroes is
|
||||
/// a valid value for the type. In particular, remember that raw
|
||||
/// pointers can be zero, but references and `NonNull<T>` cannot
|
||||
/// unless wrapped with `Option<>`.
|
||||
pub unsafe trait Zeroable: Default {
|
||||
/// SAFETY: If the trait was added to a type, then by definition
|
||||
/// this is safe.
|
||||
const ZERO: Self = unsafe { ::core::mem::MaybeUninit::<Self>::zeroed().assume_init() };
|
||||
}
|
||||
|
||||
unsafe impl Zeroable for crate::bindings::Property__bindgen_ty_1 {}
|
||||
unsafe impl Zeroable for crate::bindings::Property {}
|
||||
unsafe impl Zeroable for crate::bindings::VMStateDescription {}
|
||||
unsafe impl Zeroable for crate::bindings::MemoryRegionOps__bindgen_ty_1 {}
|
||||
unsafe impl Zeroable for crate::bindings::MemoryRegionOps__bindgen_ty_2 {}
|
Loading…
Add table
Add a link
Reference in a new issue