diff options
author | Paolo Bonzini <pbonzini@redhat.com> | 2024-10-31 14:27:36 +0100 |
---|---|---|
committer | Paolo Bonzini <pbonzini@redhat.com> | 2025-02-13 12:19:33 +0100 |
commit | ec3eba98967014f942bafb4307303d853d96e7e7 (patch) | |
tree | 7d8c3dc306db920fb6bd8b56c8fbc1c27af7e469 /rust/qemu-api/src | |
parent | 0fcccf3ff04a54d597bffcb7a42668c52a7dcec0 (diff) | |
download | qemu-ec3eba98967014f942bafb4307303d853d96e7e7.zip qemu-ec3eba98967014f942bafb4307303d853d96e7e7.tar.gz qemu-ec3eba98967014f942bafb4307303d853d96e7e7.tar.bz2 |
rust: qom: add object creation functionality
The basic object lifecycle test can now be implemented using safe code!
Reviewed-by: Zhao Liu <zhao1.liu@intel.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Diffstat (limited to 'rust/qemu-api/src')
-rw-r--r-- | rust/qemu-api/src/prelude.rs | 1 | ||||
-rw-r--r-- | rust/qemu-api/src/qom.rs | 23 |
2 files changed, 22 insertions, 2 deletions
diff --git a/rust/qemu-api/src/prelude.rs b/rust/qemu-api/src/prelude.rs index 2dc86e1..3df6a5c 100644 --- a/rust/qemu-api/src/prelude.rs +++ b/rust/qemu-api/src/prelude.rs @@ -12,6 +12,7 @@ pub use crate::qom::Object; pub use crate::qom::ObjectCast; pub use crate::qom::ObjectCastMut; pub use crate::qom::ObjectDeref; +pub use crate::qom::ObjectClassMethods; pub use crate::qom::ObjectMethods; pub use crate::qom::ObjectType; diff --git a/rust/qemu-api/src/qom.rs b/rust/qemu-api/src/qom.rs index 404446d..3e63cb3 100644 --- a/rust/qemu-api/src/qom.rs +++ b/rust/qemu-api/src/qom.rs @@ -66,8 +66,8 @@ pub use bindings::{Object, ObjectClass}; use crate::{ bindings::{ - self, object_dynamic_cast, object_get_class, object_get_typename, object_ref, object_unref, - TypeInfo, + self, object_dynamic_cast, object_get_class, object_get_typename, object_new, object_ref, + object_unref, TypeInfo, }, cell::bql_locked, }; @@ -759,6 +759,24 @@ impl<T: IsA<Object>> fmt::Debug for Owned<T> { } } +/// Trait for class methods exposed by the Object class. The methods can be +/// called on all objects that have the trait `IsA<Object>`. +/// +/// The trait should only be used through the blanket implementation, +/// which guarantees safety via `IsA` +pub trait ObjectClassMethods: IsA<Object> { + /// Return a new reference counted instance of this class + fn new() -> Owned<Self> { + assert!(bql_locked()); + // SAFETY: the object created by object_new is allocated on + // the heap and has a reference count of 1 + unsafe { + let obj = &*object_new(Self::TYPE_NAME.as_ptr()); + Owned::from_raw(obj.unsafe_cast::<Self>()) + } + } +} + /// Trait for methods exposed by the Object class. The methods can be /// called on all objects that have the trait `IsA<Object>`. /// @@ -799,4 +817,5 @@ where } } +impl<T> ObjectClassMethods for T where T: IsA<Object> {} impl<R: ObjectDeref> ObjectMethods for R where R::Target: IsA<Object> {} |