Improve AnyScope API (#2445)

* Improve AnyScope API

Signed-off-by: Aaron Erhardt <aaron.erhardt@t-online.de>

* Make find_parent_scope public

Signed-off-by: Aaron Erhardt <aaron.erhardt@t-online.de>
This commit is contained in:
Aaron Erhardt 2022-02-26 13:00:44 +01:00 committed by GitHub
parent 6fc9ef489c
commit 36058d455c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -113,24 +113,35 @@ impl AnyScope {
}
/// Attempts to downcast into a typed scope
///
/// # Panics
///
/// If the self value can't be cast into the target type.
pub fn downcast<COMP: BaseComponent>(self) -> Scope<COMP> {
let state = self.state.borrow();
state
.as_ref()
.map(|m| {
m.inner
.as_any()
.downcast_ref::<CompStateInner<COMP>>()
.unwrap()
.context
.link()
.clone()
})
.unwrap()
self.try_downcast::<COMP>().unwrap()
}
pub(crate) fn find_parent_scope<C: BaseComponent>(&self) -> Option<Scope<C>> {
/// Attempts to downcast into a typed scope
///
/// Returns [`None`] if the self value can't be cast into the target type.
pub fn try_downcast<COMP: BaseComponent>(self) -> Option<Scope<COMP>> {
let state = self.state.borrow();
state.as_ref().map(|m| {
m.inner
.as_any()
.downcast_ref::<CompStateInner<COMP>>()
.unwrap()
.context
.link()
.clone()
})
}
/// Attempts to find a parent scope of a certain type
///
/// Returns [`None`] if no parent scope with the specified type was found.
pub fn find_parent_scope<C: BaseComponent>(&self) -> Option<Scope<C>> {
let expected_type_id = TypeId::of::<C>();
iter::successors(Some(self), |scope| scope.get_parent())
.filter(|scope| scope.get_type_id() == &expected_type_id)