Skip to main content

datex_core/shared_wrappers/shared/
to_shared.rs

1use crate::{
2    runtime::{
3        Runtime, cache::shared_references_cache::SharedReferencesCache,
4        pointer_address_provider::SelfOwnedPointerAddressProvider,
5    },
6    shared_values::{OwnedSharedContainer, SharedContainerMutability},
7    shared_wrappers::shared::{shared_owned::Shared, shared_ref::SharedRef},
8    values::core_values::native::DatexNative,
9};
10
11pub trait ToShared: DatexNative + Sized {
12    fn shared_with_cache_and_address_provider(
13        self,
14        cache: &mut SharedReferencesCache,
15        provider: &mut SelfOwnedPointerAddressProvider,
16    ) -> Shared<Self> {
17        Shared::try_from(OwnedSharedContainer::new_native(
18            self,
19            SharedContainerMutability::Mutable,
20            provider,
21            cache,
22        ))
23        .unwrap() // TODO: can we always unwrap safely here?
24    }
25
26    /// Creates a [Shared] value containing [Self]
27    fn shared(self, runtime: &Runtime) -> Shared<Self> {
28        let mut cache = runtime.shared_references_cache_refcell().borrow_mut();
29        let mut provider = runtime.pointer_address_provider_mut();
30        self.shared_with_cache_and_address_provider(&mut cache, &mut provider)
31    }
32
33    fn shared_ref_with_cache_and_address_provider(
34        self,
35        cache: &mut SharedReferencesCache,
36        provider: &mut SelfOwnedPointerAddressProvider,
37    ) -> SharedRef<Self> {
38        SharedRef::try_from(OwnedSharedContainer::new_native(
39            self,
40            SharedContainerMutability::Mutable,
41            provider,
42            cache,
43        ))
44        .unwrap() // TODO: can we always unwrap safely here?
45    }
46
47    /// Creates a [SharedRef] value containing [Self]
48    fn shared_ref(self, runtime: &Runtime) -> SharedRef<Self> {
49        let mut cache = runtime.shared_references_cache_refcell().borrow_mut();
50        let mut provider = runtime.pointer_address_provider_mut();
51        self.shared_ref_with_cache_and_address_provider(
52            &mut cache,
53            &mut provider,
54        )
55    }
56}
57
58/// Auto implementation of ToShared for all types that implement DatexNative and are Sized.
59impl<T> ToShared for T where T: DatexNative + Sized {}