From dd64226dc11bdacfd60de28b3cee67d7591c20be Mon Sep 17 00:00:00 2001 From: Simon Hausmann Date: Wed, 2 Dec 2020 14:59:56 +0100 Subject: [PATCH] Implement sixtyfps::Weak This is the counter-part to the strongly referencing type the compiler generates for components. --- api/sixtyfps-rs/lib.rs | 42 +++++++++++++++++++++++++++++ sixtyfps_compiler/generator/rust.rs | 11 ++++++++ 2 files changed, 53 insertions(+) diff --git a/api/sixtyfps-rs/lib.rs b/api/sixtyfps-rs/lib.rs index 3b952c324..d6a7a18f3 100644 --- a/api/sixtyfps-rs/lib.rs +++ b/api/sixtyfps-rs/lib.rs @@ -305,6 +305,48 @@ impl ComponentWeakHandle { } } +/// This trait describes the conversion of a strongly referenced SixtyFPS component, +/// held by a [vtable::VRc] into a weak reference. +pub trait IntoWeak { + /// The type of the generated component. + type Inner; + /// Returns a new weak pointer. + fn as_weak(&self) -> Weak + where + Self: Sized; + + /// Internal function used when upgrading a weak reference to a strong one. + fn from_inner(_: vtable::VRc) -> Self; +} + +/// Struct that's used to hold weak references for SixtyFPS components. +pub struct Weak { + inner: vtable::VWeak, +} + +impl Weak { + #[doc(hidden)] + pub fn new(rc: &vtable::VRc) -> Self { + Self { inner: vtable::VRc::downgrade(&rc) } + } + + /// Returns a new strongly referenced component if some other instance still + /// holds a strong reference. Otherwise, returns None. + pub fn upgrade(&self) -> Option + where + T: IntoWeak, + { + self.inner.upgrade().map(|inner| T::from_inner(inner)) + } + + /// Convenience function that returns a new stronlyg referenced component if + /// some other instance still holds a strong reference. Otherwise, this function + /// panics. + pub fn unwrap(&self) -> T { + self.upgrade().unwrap() + } +} + /// This module contains functions useful for unit tests pub mod testing { /// This trait gives access to the underyling Window of a component for the diff --git a/sixtyfps_compiler/generator/rust.rs b/sixtyfps_compiler/generator/rust.rs index 3c8fad6c2..c5f33e3a2 100644 --- a/sixtyfps_compiler/generator/rust.rs +++ b/sixtyfps_compiler/generator/rust.rs @@ -107,6 +107,7 @@ pub fn generate(doc: &Document, diag: &mut BuildDiagnostics) -> Option sixtyfps::Weak { + sixtyfps::Weak::new(&self.0) + } + + fn from_inner(inner: vtable::VRc) -> Self { + Self(inner) + } + } )) } else { None