From 72a74ab22000ff66d134cff775fdfab658fb6e90 Mon Sep 17 00:00:00 2001 From: Tomoaki Kawada Date: Fri, 30 Aug 2024 11:03:42 +0900 Subject: [PATCH] glib: Do not use `end_unsafe` in `>::from` While this method consumes a given `VariantDict`, the underlying object could still be accessed through other clones because of the reference counted clone semantics. --- glib/src/variant_dict.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/glib/src/variant_dict.rs b/glib/src/variant_dict.rs index 66a89e3e37da..8a7a334ee97d 100644 --- a/glib/src/variant_dict.rs +++ b/glib/src/variant_dict.rs @@ -213,9 +213,15 @@ impl ToVariant for VariantDict { } impl From for Variant { + // rustdoc-stripper-ignore-next + /// Consume a given `VariantDict` and call [`VariantDict::end`] on it. + /// + /// Note: While this method consumes the `VariantDict`, the underlying + /// object could still be accessed through other clones because of the + /// reference counted clone semantics. #[inline] fn from(d: VariantDict) -> Self { - unsafe { d.end_unsafe() } + d.end() } } @@ -251,6 +257,28 @@ mod test { let _dict2: VariantDict = var.into(); } + #[test] + fn into_variant_roundtrip() { + let dict1 = VariantDict::default(); + let dict2 = dict1.clone(); + dict1.insert_value("one", &(1u8.to_variant())); + + assert_eq!(dict1.lookup::("one").unwrap(), Some(1u8)); + assert_eq!(dict2.lookup::("one").unwrap(), Some(1u8)); + + // Convert it into `Variant` + let dict: Variant = dict1.into(); + + // While we can still access the `VariantDict` via `dict2`, + // it should be empty now + assert_eq!(dict2.lookup::("one").unwrap(), None); + + // Convert it back + let dict3: VariantDict = dict.into(); + + assert_eq!(dict3.lookup::("one").unwrap(), Some(1u8)); + } + #[test] fn create_populate_destroy() { let dict = VariantDict::default();