routing/bedrock/
weak_instance_token_ext.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::component_instance::{
    ComponentInstanceInterface, ExtendedInstanceInterface, WeakComponentInstanceInterface,
    WeakExtendedInstanceInterface,
};
use crate::error::ComponentInstanceError;
use moniker::ExtendedMoniker;
use sandbox::WeakInstanceToken;
use std::sync::Arc;

/// A trait to add functions WeakComponentInstancethat know about the component
/// manager types.
pub trait WeakInstanceTokenExt<C: ComponentInstanceInterface + 'static> {
    /// Upgrade this token to the underlying instance.
    fn to_instance(self) -> WeakExtendedInstanceInterface<C>;

    /// Get a reference to the underlying instance.
    fn as_ref(&self) -> &WeakExtendedInstanceInterface<C>;

    /// Get a strong reference to the underlying instance.
    fn upgrade(&self) -> Result<ExtendedInstanceInterface<C>, ComponentInstanceError>;

    /// Get the moniker for this component.
    fn moniker(&self) -> ExtendedMoniker;
}

impl<C: ComponentInstanceInterface + 'static> WeakInstanceTokenExt<C> for WeakInstanceToken {
    fn to_instance(self) -> WeakExtendedInstanceInterface<C> {
        self.as_ref().clone()
    }

    fn as_ref(&self) -> &WeakExtendedInstanceInterface<C> {
        match self.inner.as_any().downcast_ref::<WeakExtendedInstanceInterface<C>>() {
            Some(instance) => &instance,
            None => panic!(),
        }
    }

    fn upgrade(&self) -> Result<ExtendedInstanceInterface<C>, ComponentInstanceError> {
        self.as_ref().upgrade()
    }

    fn moniker(&self) -> ExtendedMoniker {
        WeakInstanceTokenExt::<C>::as_ref(self).extended_moniker()
    }
}

/// Returns a token representing an invalid component. For testing.
pub fn test_invalid_instance_token<C: ComponentInstanceInterface + 'static>() -> WeakInstanceToken {
    WeakComponentInstanceInterface::<C>::invalid().into()
}

impl<C: ComponentInstanceInterface + 'static> From<WeakExtendedInstanceInterface<C>>
    for WeakInstanceToken
{
    fn from(instance: WeakExtendedInstanceInterface<C>) -> Self {
        Self { inner: Arc::new(instance) }
    }
}

impl<C: ComponentInstanceInterface + 'static> From<WeakComponentInstanceInterface<C>>
    for WeakInstanceToken
{
    fn from(instance: WeakComponentInstanceInterface<C>) -> Self {
        Self::from(WeakExtendedInstanceInterface::<C>::Component(instance))
    }
}