Skip to main content

routing/bedrock/
weak_instance_token_ext.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::component_instance::{
6    ComponentInstanceInterface, ExtendedInstanceInterface, WeakComponentInstanceInterface,
7    WeakExtendedInstanceInterface,
8};
9use crate::error::ComponentInstanceError;
10use moniker::ExtendedMoniker;
11use runtime_capabilities::WeakInstanceToken;
12use std::sync::Arc;
13
14/// A trait to add functions WeakComponentInstancethat know about the component
15/// manager types.
16pub trait WeakInstanceTokenExt<C: ComponentInstanceInterface + 'static> {
17    /// Upgrade this token to the underlying instance.
18    fn to_instance(self) -> WeakExtendedInstanceInterface<C>;
19
20    /// Get a reference to the underlying instance.
21    fn as_instance_ref(&self) -> &WeakExtendedInstanceInterface<C>;
22
23    /// Get a strong reference to the underlying instance.
24    fn upgrade(&self) -> Result<ExtendedInstanceInterface<C>, ComponentInstanceError>;
25
26    /// Get the moniker for this component.
27    fn moniker(&self) -> ExtendedMoniker;
28}
29
30impl<C: ComponentInstanceInterface + 'static> WeakInstanceTokenExt<C> for Arc<WeakInstanceToken> {
31    fn to_instance(self) -> WeakExtendedInstanceInterface<C> {
32        self.as_instance_ref().clone()
33    }
34
35    fn as_instance_ref(&self) -> &WeakExtendedInstanceInterface<C> {
36        match self.inner.as_any().downcast_ref::<WeakExtendedInstanceInterface<C>>() {
37            Some(instance) => &instance,
38            None => panic!(),
39        }
40    }
41
42    fn upgrade(&self) -> Result<ExtendedInstanceInterface<C>, ComponentInstanceError> {
43        self.as_instance_ref().upgrade()
44    }
45
46    fn moniker(&self) -> ExtendedMoniker {
47        WeakInstanceTokenExt::<C>::as_instance_ref(self).extended_moniker()
48    }
49}
50
51/// Returns a token representing an invalid component. For testing.
52pub fn test_invalid_instance_token<C: ComponentInstanceInterface + 'static>()
53-> Arc<WeakInstanceToken> {
54    WeakComponentInstanceInterface::<C>::invalid().into()
55}
56
57impl<C: ComponentInstanceInterface + 'static> From<WeakExtendedInstanceInterface<C>>
58    for Arc<WeakInstanceToken>
59{
60    fn from(instance: WeakExtendedInstanceInterface<C>) -> Self {
61        Arc::new(WeakInstanceToken { inner: Box::new(instance) })
62    }
63}
64
65impl<C: ComponentInstanceInterface + 'static> From<WeakComponentInstanceInterface<C>>
66    for Arc<WeakInstanceToken>
67{
68    fn from(instance: WeakComponentInstanceInterface<C>) -> Self {
69        Self::from(WeakExtendedInstanceInterface::<C>::Component(instance))
70    }
71}