qemu-devel.nongnu.org archive mirror
 help / color / mirror / Atom feed
From: Paolo Bonzini <pbonzini@redhat.com>
To: qemu-devel@nongnu.org
Cc: "Pierrick Bouvier" <pierrick.bouvier@linaro.org>,
	"Manos Pitsidianakis" <manos.pitsidianakis@linaro.org>,
	"Peter Maydell" <peter.maydell@linaro.org>,
	"Alex Bennée" <alex.bennee@linaro.org>,
	"Daniel P . Berrangé" <berrange@redhat.com>,
	"Marc-André Lureau" <marcandre.lureau@redhat.com>,
	"Hanna Czenczek" <hreitz@redhat.com>,
	"Stefan Hajnoczi" <stefanha@redhat.com>
Subject: [PATCH 07/14] rust: define wrappers for methods of the QOM Object class
Date: Mon,  1 Jul 2024 16:58:39 +0200	[thread overview]
Message-ID: <20240701145853.1394967-8-pbonzini@redhat.com> (raw)
In-Reply-To: <20240701145853.1394967-1-pbonzini@redhat.com>

Provide a trait that can be used to invoke methods of the QOM object
class.  The trait extends Deref and has a blanket implementation for any
type that dereferences to IsA<Object>.  This way, it can be used on any
struct that dereferences to Object or a subclass.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
---
 qemu/src/lib.rs        |  2 +
 qemu/src/qom/object.rs | 92 ++++++++++++++++++++++++++++++++++++++++++
 qemu/src/qom/refs.rs   |  8 ++++
 3 files changed, 102 insertions(+)

diff --git a/qemu/src/lib.rs b/qemu/src/lib.rs
index 0d91623..a6e7b17 100644
--- a/qemu/src/lib.rs
+++ b/qemu/src/lib.rs
@@ -5,6 +5,8 @@ pub mod bindings;
 pub use bindings::Object;
 
 pub mod qom;
+pub use qom::object::ObjectClassMethods;
+pub use qom::object::ObjectMethods;
 pub use qom::object::ObjectType;
 pub use qom::refs::ObjectCast;
 pub use qom::refs::Owned;
diff --git a/qemu/src/qom/object.rs b/qemu/src/qom/object.rs
index bd6b957..4e84e29 100644
--- a/qemu/src/qom/object.rs
+++ b/qemu/src/qom/object.rs
@@ -2,12 +2,26 @@
 //!
 //! @author Paolo Bonzini
 
+use std::borrow::Cow;
 use std::ffi::CStr;
+use std::fmt;
+use std::ops::Deref;
 
+use crate::bindings::object_get_typename;
+use crate::bindings::object_property_add_child;
+use crate::bindings::object_new;
+use crate::bindings::object_unparent;
 use crate::bindings::Object;
 
 use crate::qom_isa;
 
+use crate::qom::refs::IsA;
+use crate::qom::refs::ObjectCast;
+use crate::qom::refs::Owned;
+
+use crate::util::foreign::CloneToForeign;
+use crate::util::foreign::FromForeign;
+
 /// Trait exposed by all structs corresponding to QOM objects.
 /// Defines "class methods" for the class.  Usually these can be
 /// implemented on the class itself; here, using a trait allows
@@ -31,4 +45,82 @@ unsafe impl ObjectType for Object {
     const TYPE: &'static CStr = c"object";
 }
 
+// ------------------------------
+// Object class
+
 qom_isa!(Object);
+
+/// 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> {
+        // 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.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>`.
+///
+/// The trait should only be used through the blanket implementation,
+/// which guarantees safety via `IsA`
+pub trait ObjectMethods: Deref
+where
+    Self::Target: IsA<Object>,
+{
+    /// Return the name of the type of `self`
+    fn typename(&self) -> Cow<'_, str> {
+        let obj = self.upcast::<Object>();
+        // SAFETY: safety of this is the requirement for implementing IsA
+        // The result of the C API has static lifetime
+        unsafe {
+            Cow::cloned_from_foreign(object_get_typename(obj.as_mut_ptr()))
+        }
+    }
+
+    /// Add an object as a child of the receiver.
+    fn property_add_child<T: ObjectType>(&self, name: &str, child: Owned<T>)
+    {
+        let obj = self.upcast::<Object>();
+        let name = name.clone_to_foreign();
+        unsafe {
+            // SAFETY: casting to object is always safe even if `child`'s
+            // target type is an interface type
+            let child = child.unsafe_cast::<Object>();
+            object_property_add_child(obj.as_mut_ptr(),
+                                      name.as_ptr(),
+                                      child.as_mut_ptr());
+
+            // object_property_add_child() added a reference of its own;
+            // dropping the one in `child` is the common case.
+        }
+    }
+
+    /// Remove the object from the QOM tree
+    fn unparent(&self) {
+        let obj = self.upcast::<Object>();
+        // SAFETY: safety of this is the requirement for implementing IsA
+        unsafe {
+            object_unparent(obj.as_mut_ptr());
+        }
+    }
+
+    /// Convenience function for implementing the Debug trait
+    fn debug_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        f.debug_tuple(&self.typename())
+            .field(&(self as *const Self))
+            .finish()
+    }
+}
+
+impl<R> ObjectClassMethods for R where R: IsA<Object> {}
+impl<R: Deref> ObjectMethods for R where R::Target: IsA<Object> {}
diff --git a/qemu/src/qom/refs.rs b/qemu/src/qom/refs.rs
index a319bde..431ef0a 100644
--- a/qemu/src/qom/refs.rs
+++ b/qemu/src/qom/refs.rs
@@ -6,9 +6,11 @@ use crate::bindings::object_dynamic_cast;
 use crate::bindings::Object;
 use crate::bindings::{object_ref, object_unref};
 
+use crate::qom::object::ObjectMethods;
 use crate::qom::object::ObjectType;
 
 use std::borrow::Borrow;
+use std::fmt::{self, Debug};
 use std::mem::ManuallyDrop;
 use std::ops::Deref;
 use std::ptr::NonNull;
@@ -272,3 +274,9 @@ impl<T: ObjectType> Drop for Owned<T> {
         }
     }
 }
+
+impl<T: IsA<Object>> Debug for Owned<T> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        self.deref().debug_fmt(f)
+    }
+}
-- 
2.45.2



  parent reply	other threads:[~2024-07-01 15:00 UTC|newest]

Thread overview: 27+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2024-07-01 14:58 [PATCH 00/14] rust: example of bindings code for Rust in QEMU Paolo Bonzini
2024-07-01 14:58 ` [PATCH 01/14] add skeleton Paolo Bonzini
2024-07-01 14:58 ` [PATCH 02/14] set expectations Paolo Bonzini
2024-07-01 14:58 ` [PATCH 03/14] rust: define traits and pointer wrappers to convert from/to C representations Paolo Bonzini
2024-07-03 12:48   ` Marc-André Lureau
2024-07-03 12:58     ` Marc-André Lureau
2024-07-03 15:55     ` Paolo Bonzini
2024-09-27 16:09   ` Kevin Wolf
2024-09-27 20:19     ` Paolo Bonzini
2024-09-27 19:36   ` Stefan Hajnoczi
2024-09-27 20:26     ` Paolo Bonzini
2025-05-26 12:35       ` Paolo Bonzini
2024-07-01 14:58 ` [PATCH 04/14] rust: add tests for util::foreign Paolo Bonzini
2024-07-01 14:58 ` [PATCH 05/14] rust: define wrappers for Error Paolo Bonzini
2024-07-01 14:58 ` [PATCH 06/14] rust: define wrappers for basic QOM concepts Paolo Bonzini
2024-07-01 14:58 ` Paolo Bonzini [this message]
2024-07-01 14:58 ` [PATCH 08/14] rust: define wrappers for methods of the QOM Device class Paolo Bonzini
2024-07-01 14:58 ` [PATCH 09/14] rust: add idiomatic bindings to define Object subclasses Paolo Bonzini
2024-07-01 14:58 ` [PATCH 10/14] rust: add idiomatic bindings to define Device subclasses Paolo Bonzini
2024-07-01 14:58 ` [PATCH 11/14] rust: replace std::ffi::c_char with libc::c_char Paolo Bonzini
2024-07-01 14:58 ` [PATCH 12/14] rust: replace c"" literals with cstr crate Paolo Bonzini
2024-07-01 14:58 ` [PATCH 13/14] rust: introduce alternative to offset_of! Paolo Bonzini
2024-07-01 14:58 ` [PATCH 14/14] rust: use version of toml_edit that does not require new Rust Paolo Bonzini
2024-07-04 19:26 ` [PATCH 00/14] rust: example of bindings code for Rust in QEMU Pierrick Bouvier
2024-07-05  8:06   ` Paolo Bonzini
2024-07-05 18:52     ` Pierrick Bouvier
2024-07-05 21:08       ` Paolo Bonzini

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20240701145853.1394967-8-pbonzini@redhat.com \
    --to=pbonzini@redhat.com \
    --cc=alex.bennee@linaro.org \
    --cc=berrange@redhat.com \
    --cc=hreitz@redhat.com \
    --cc=manos.pitsidianakis@linaro.org \
    --cc=marcandre.lureau@redhat.com \
    --cc=peter.maydell@linaro.org \
    --cc=pierrick.bouvier@linaro.org \
    --cc=qemu-devel@nongnu.org \
    --cc=stefanha@redhat.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).