From fdcf944d75f47fb505a3796aeaa48db8328b31e3 Mon Sep 17 00:00:00 2001 From: Zander Brown Date: Mon, 11 Dec 2023 22:20:42 +0000 Subject: [PATCH] glib: Add upgrade_or_insert{_with} to WeakRefs Avoids some boilerplate when implementing things like single-window apps, where you don't really care if the object was already set, you just need an object --- glib/src/object.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/glib/src/object.rs b/glib/src/object.rs index c10fefe2bd8b..b48b9a95445c 100644 --- a/glib/src/object.rs +++ b/glib/src/object.rs @@ -3429,6 +3429,35 @@ impl WeakRef { } } } + + // rustdoc-stripper-ignore-next + /// Try to upgrade this weak reference to a strong reference. + /// + /// If the stored object was already destroyed or no object was set, the + /// reference is updated to `value`, which is then returned + #[inline] + pub fn upgrade_or_insert(&self, value: T) -> T { + self.upgrade_or_insert_with(|| value) + } + + // rustdoc-stripper-ignore-next + /// Try to upgrade this weak reference to a strong reference. + /// + /// If the stored object was already destroyed or no object was set, the + /// reference is updated to the result of `f`, which is then returned + #[inline] + pub fn upgrade_or_insert_with(&self, f: F) -> T + where + F: FnOnce() -> T, + { + if let Some(object) = self.upgrade() { + object + } else { + let object = f(); + self.set(Some(&object)); + object + } + } } impl Drop for WeakRef {