On Wed, Oct 01, 2025 at 10:00:41AM +0200, Paolo Bonzini wrote:
> Date: Wed, 1 Oct 2025 10:00:41 +0200
> From: Paolo Bonzini <[email protected]>
> Subject: [PATCH 04/14] rust: add Serialize implementation for QObject
> X-Mailer: git-send-email 2.51.0
>
> This allows QObject to be converted to other formats, for example
> JSON via serde_json.
>
> This is not too useful, since QObjects are consumed by
> C code or deserialized into structs, but it can be used for testing
> and it is part of the full implementation of a serde format.
>
> Co-authored-by: Marc-André Lureau <[email protected]>
> Signed-off-by: Marc-André Lureau <[email protected]>
> Signed-off-by: Paolo Bonzini <[email protected]>
> ---
> rust/Cargo.lock | 1 +
> rust/util/Cargo.toml | 1 +
> rust/util/meson.build | 3 +-
> rust/util/src/qobject/mod.rs | 4 +-
> rust/util/src/qobject/serialize.rs | 59 ++++++++++++++++++++++++++++++
> 5 files changed, 65 insertions(+), 3 deletions(-)
> create mode 100644 rust/util/src/qobject/serialize.rs
...
> +impl Serialize for QObject {
> + #[inline]
> + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
> + where
> + S: ::serde::Serializer,
> + {
> + match_qobject! { (self) =>
> + () => serializer.serialize_unit(),
> + bool(b) => serializer.serialize_bool(b),
> + i64(i) => serializer.serialize_i64(i),
> + u64(u) => serializer.serialize_u64(u),
> + f64(f) => serializer.serialize_f64(f),
> + CStr(cstr) => cstr.to_str().map_or_else(
> + |_| Err(ser::Error::custom("invalid UTF-8 in QString")),
> + |s| serializer.serialize_str(s),
> + ),
> + QList(l) => {
> + let mut node_ptr = unsafe { l.head.tqh_first };
> + let mut state = serializer.serialize_seq(None)?;
> + while !node_ptr.is_null() {
> + let node = unsafe { &*node_ptr };
> + let elem = unsafe {
> ManuallyDrop::new(QObject::from_raw(addr_of!(*node.value))) };
> + state.serialize_element(&*elem)?;
QObject here is always valid so it's not necessary to concern about it
is destroied by C side, and so that it's not necessary to use
cloned_from_raw here.
Reviewed-by: Zhao Liu <[email protected]>