Skip to main content

datex_core/shared_values/shared_container/
mod.rs

1//! This module contains the implementation of the shared container, which is the holder of [SharedContainerInner]
2//! and the top-level wrapper for any owned or referenced shared container.
3use crate::{
4    runtime::pointer_address_provider::SelfOwnedPointerAddressProvider,
5    shared_values::{
6        OwnedSharedContainer, PointerAddress, ReferencedSharedContainer,
7        SelfOwnedPointerAddress, SharedContainerInner,
8        SharedContainerMutability, SharedContainerOwnership,
9        base_shared_value_container::BaseSharedValueContainer,
10        errors::{
11            AccessError, UnexpectedImmutableReferenceError,
12            UnexpectedSharedContainerOwnershipError,
13        },
14        internal_traits::_ExposeRcInternal,
15    },
16    traits::{
17        apply::Apply, identity::Identity, structural_eq::StructuralEq,
18        value_eq::ValueEq,
19    },
20    values::{
21        value::Value,
22        value_container::{ValueContainer, value_key::BorrowedValueKey},
23    },
24};
25pub mod identity;
26use crate::{
27    shared_values::{
28        ReferenceMutability,
29        base_shared_value_container::observers::{
30            Observer, ObserverError, ObserverId,
31        },
32    },
33    types::type_definition::TypeDefinition,
34};
35use alloc::rc::Rc;
36use core::{
37    cell::{Ref, RefCell, RefMut},
38    fmt::{Display, Formatter},
39    hash::{Hash, Hasher},
40};
41use serde::Serializer;
42
43pub mod apply;
44pub mod serde_dif;
45/// Top-level wrapper for any owned or referenced shared container,
46/// which can either be an owned shared container or a reference to a shared container.
47#[derive(Debug)]
48pub enum SharedContainer {
49    /// An owned shared container (`shared X`). This is always points to a [SharedContainerInner::EndpointOwned]
50    Owned(OwnedSharedContainer),
51    /// A referenced shared container (`'shared X` or `'mut shared X`).
52    /// This can point to either a [SharedContainerInner::EndpointOwned] or a [SharedContainerInner::External]
53    Referenced(ReferencedSharedContainer),
54}
55
56impl SharedContainer {
57    /// Creates a new owned [SharedContainer] with an initial [ValueContainer],
58    /// a [SharedContainerMutability], and a [SelfOwnedPointerAddressProvider].
59    ///
60    /// The allowed type is inferred from the value_container's allowed type.
61    pub fn new_owned_with_inferred_allowed_type<T: Into<ValueContainer>>(
62        value_container: T,
63        mutability: SharedContainerMutability,
64        address_provider: &mut SelfOwnedPointerAddressProvider,
65    ) -> Self {
66        SharedContainer::Owned(
67            OwnedSharedContainer::new_with_inferred_allowed_type(
68                value_container,
69                mutability,
70                address_provider,
71            ),
72        )
73    }
74
75    /// Creates a new owned [SharedContainer] with an initial [ValueContainer],
76    /// a [SharedContainerMutability], and a [SelfOwnedPointerAddress].
77    ///
78    /// The allowed type is inferred from the value_container's allowed type.
79    /// # Safety
80    /// The caller must ensure that the address is not used anywhere else.
81    pub unsafe fn new_owned_with_inferred_allowed_type_unsafe<
82        T: Into<ValueContainer>,
83    >(
84        value_container: T,
85        mutability: SharedContainerMutability,
86        address: SelfOwnedPointerAddress,
87    ) -> Self {
88        SharedContainer::Owned(unsafe {
89            OwnedSharedContainer::new_with_inferred_allowed_type_unsafe(
90                value_container.into(),
91                mutability,
92                address,
93            )
94        })
95    }
96
97    /// Creates a new owned [SharedContainer] with the same contents.
98    /// # Safety
99    /// The caller must be sure, that the reference on the original self is not used later.
100    pub unsafe fn clone_unsafe(&self) -> Self {
101        match self {
102            SharedContainer::Owned(owned) => {
103                SharedContainer::Owned(unsafe { owned.clone_unsafe() })
104            }
105            SharedContainer::Referenced(referenced) => {
106                SharedContainer::Referenced(referenced.clone())
107            }
108        }
109    }
110
111    pub fn inner(&self) -> Ref<'_, SharedContainerInner> {
112        match self {
113            SharedContainer::Owned(owned) => owned.inner(),
114            SharedContainer::Referenced(referenced) => referenced.inner(),
115        }
116    }
117
118    pub fn inner_mut(&self) -> RefMut<'_, SharedContainerInner> {
119        match self {
120            SharedContainer::Owned(owned) => owned.inner_mut(),
121            SharedContainer::Referenced(referenced) => referenced.inner_mut(),
122        }
123    }
124
125    /// Gets a [Ref] to the currently assigned [BaseSharedValueContainer] of the shared container (not resolved recursively)
126    pub fn base_shared_container(&self) -> Ref<'_, BaseSharedValueContainer> {
127        match self {
128            SharedContainer::Owned(owned) => owned.base_shared_container(),
129            SharedContainer::Referenced(referenced) => {
130                referenced.base_shared_container()
131            }
132        }
133    }
134
135    /// Adds an observer to this shared container that will be notified on value changes.
136    pub fn observe(
137        &self,
138        observer: Observer,
139    ) -> Result<ObserverId, ObserverError> {
140        self.base_shared_container_mut().observe(observer)
141    }
142
143    pub fn unobserve(
144        &self,
145        observer_id: ObserverId,
146    ) -> Result<(), ObserverError> {
147        self.base_shared_container_mut().unobserve(observer_id)
148    }
149
150    /// Gets a [RefMut] to the currently assigned [BaseSharedValueContainer] of the shared container (not resolved recursively)
151    pub fn base_shared_container_mut(
152        &self,
153    ) -> RefMut<'_, BaseSharedValueContainer> {
154        match self {
155            SharedContainer::Owned(owned) => owned.base_shared_container_mut(),
156            SharedContainer::Referenced(referenced) => {
157                referenced.base_shared_container_mut()
158            }
159        }
160    }
161
162    /// Gets a [Ref] to the currently assigned [ValueContainer] of the shared container (not resolved recursively)
163    pub fn value_container(&self) -> Ref<'_, ValueContainer> {
164        match self {
165            SharedContainer::Owned(owned) => owned.value_container(),
166            SharedContainer::Referenced(referenced) => {
167                referenced.value_container()
168            }
169        }
170    }
171
172    /// Gets a [Ref] to the currently assigned allowed [TypeDefinition] of the shared container (not resolved recursively)
173    pub fn allowed_type(&self) -> Ref<'_, TypeDefinition> {
174        match self {
175            SharedContainer::Owned(owned) => owned.allowed_type(),
176            SharedContainer::Referenced(referenced) => {
177                referenced.allowed_type()
178            }
179        }
180    }
181
182    /// Gets the current actual [TypeDefinition] of the collapsed inner [Value]
183    pub fn actual_type(&self) -> TypeDefinition {
184        self.with_collapsed_value(|value| value.actual_type())
185    }
186
187    /// Gets a [RefMut] to the currently assigned [ValueContainer] of the shared container (not resolved recursively)
188    pub fn value_container_mut(&self) -> RefMut<'_, ValueContainer> {
189        match self {
190            SharedContainer::Owned(owned) => owned.value_container_mut(),
191            SharedContainer::Referenced(referenced) => {
192                referenced.value_container_mut()
193            }
194        }
195    }
196
197    /// Get the [SharedContainerMutability] of the inner container.
198    pub fn container_mutability(&self) -> SharedContainerMutability {
199        match self {
200            SharedContainer::Owned(owned) => owned.container_mutability(),
201            SharedContainer::Referenced(referenced) => {
202                referenced.container_mutability()
203            }
204        }
205    }
206
207    /// Calls the provided callback with a mut reference to the recursively collapsed inner value of the shared container
208    pub fn with_collapsed_value_mut<R>(
209        &self,
210        f: impl FnOnce(&mut Value) -> R,
211    ) -> R {
212        self.base_shared_container_mut().with_collapsed_value_mut(f)
213    }
214
215    /// Calls the provided callback with a reference to the recursively collapsed inner value of the shared container
216    pub fn with_collapsed_value<R>(&self, f: impl FnOnce(&Value) -> R) -> R {
217        self.base_shared_container().with_collapsed_value(f)
218    }
219
220    pub fn try_get_property<'a>(
221        &self,
222        key: impl Into<BorrowedValueKey<'a>>,
223    ) -> Result<ValueContainer, AccessError> {
224        self.base_shared_container().try_get_property(key)
225    }
226
227    pub fn pointer_address(&self) -> PointerAddress {
228        match self {
229            SharedContainer::Owned(owned) => {
230                PointerAddress::SelfOwned(owned.pointer_address().clone())
231            }
232            SharedContainer::Referenced(referenced) => {
233                referenced.pointer_address()
234            }
235        }
236    }
237
238    /// Creates a new immutable [ReferencedSharedContainer] pointing to the same inner value as self.
239    pub fn derive_immutable_reference(&self) -> ReferencedSharedContainer {
240        match self {
241            SharedContainer::Owned(owned) => owned.derive_immutable_reference(),
242            SharedContainer::Referenced(referenced) => {
243                referenced.derive_immutable_reference()
244            }
245        }
246    }
247    /// Tries to create a new mutable or immutable [ReferencedSharedContainer] pointing to the same inner value as this [OwnedSharedContainer].
248    /// Returns an [Err] if the requested mutability is [ReferenceMutability::Mutable],
249    /// but the current reference_mutability is [ReferenceMutability::Immutable] or the container itself is not mutable
250    pub fn try_derive_reference_with_mutability(
251        &self,
252        mutability: ReferenceMutability,
253    ) -> Result<ReferencedSharedContainer, UnexpectedImmutableReferenceError>
254    {
255        match mutability {
256            ReferenceMutability::Immutable => {
257                Ok(self.derive_immutable_reference())
258            }
259            ReferenceMutability::Mutable => self.try_derive_mutable_reference(),
260        }
261    }
262
263    /// Tries to create a new mutable [ReferencedSharedContainer] pointing to the same inner value as this [OwnedSharedContainer].
264    /// Returns an [Err] if the current reference_mutability is [ReferenceMutability::Immutable] or the container itself is not mutable
265    pub fn try_derive_mutable_reference(
266        &self,
267    ) -> Result<ReferencedSharedContainer, UnexpectedImmutableReferenceError>
268    {
269        match self {
270            SharedContainer::Owned(owned) => owned
271                .try_derive_mutable_reference()
272                .map_err(|_| UnexpectedImmutableReferenceError),
273            SharedContainer::Referenced(referenced) => {
274                referenced.try_derive_mutable_reference()
275            }
276        }
277    }
278
279    /// Returns the owned shared container if it is owned, otherwise returns an error.
280    pub fn try_get_owned(
281        &self,
282    ) -> Result<&OwnedSharedContainer, UnexpectedSharedContainerOwnershipError>
283    {
284        match self {
285            SharedContainer::Owned(owned) => Ok(owned),
286            SharedContainer::Referenced(reference) => {
287                Err(UnexpectedSharedContainerOwnershipError {
288                    actual: SharedContainerOwnership::Referenced(
289                        reference.reference_mutability(),
290                    ),
291                    expected: SharedContainerOwnership::Owned,
292                })
293            }
294        }
295    }
296
297    /// Clones the shared container as a mutable reference if possible, otherwise as an immutable reference
298    pub fn derive_reference_with_max_mutability(
299        &self,
300    ) -> ReferencedSharedContainer {
301        self.try_derive_mutable_reference()
302            .unwrap_or_else(|_| self.derive_immutable_reference())
303    }
304
305    /// Checks if the shared container can be mutated by the local endpoint
306    pub fn can_mutate(&self) -> bool {
307        match self {
308            SharedContainer::Owned(owned) => owned.can_mutate(),
309            SharedContainer::Referenced(referenced) => referenced.can_mutate(),
310        }
311    }
312
313    /// Returns the [SharedContainerOwnership] of this shared container
314    pub fn ownership(&self) -> SharedContainerOwnership {
315        match self {
316            SharedContainer::Owned(_owned) => SharedContainerOwnership::Owned,
317            SharedContainer::Referenced(referenced) => {
318                SharedContainerOwnership::Referenced(
319                    referenced.reference_mutability(),
320                )
321            }
322        }
323    }
324}
325
326/// Custom clone implementation for [SharedContainer].
327/// A [SharedContainer::Owned] cannot be cloned as is, only a new reference can be created
328/// A [SharedContainer::Referenced] can be cloned normally
329impl Clone for SharedContainer {
330    fn clone(&self) -> Self {
331        match self {
332            // An owned container cannot be cloned, only a new reference can be created
333            SharedContainer::Owned(owned) => {
334                SharedContainer::Referenced(owned.derive_with_max_mutability())
335            }
336            // A referenced container can be cloned
337            SharedContainer::Referenced(referenced) => {
338                SharedContainer::Referenced(referenced.clone())
339            }
340        }
341    }
342}
343
344impl Display for SharedContainer {
345    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
346        match self {
347            SharedContainer::Owned(owned) => write!(f, "{}", owned),
348            SharedContainer::Referenced(referenced) => {
349                write!(f, "{}", referenced)
350            }
351        }
352    }
353}
354
355pub mod datex_proxy;
356pub mod equality;
357
358impl From<OwnedSharedContainer> for SharedContainer {
359    fn from(value: OwnedSharedContainer) -> Self {
360        SharedContainer::Owned(value)
361    }
362}
363
364impl From<ReferencedSharedContainer> for SharedContainer {
365    fn from(value: ReferencedSharedContainer) -> Self {
366        SharedContainer::Referenced(value)
367    }
368}
369
370impl _ExposeRcInternal for SharedContainer {
371    type Shared = SharedContainerInner;
372    fn get_rc_internal(&self) -> &Rc<RefCell<Self::Shared>> {
373        match self {
374            SharedContainer::Owned(owned) => owned.get_rc_internal(),
375            SharedContainer::Referenced(referenced) => {
376                referenced.get_rc_internal()
377            }
378        }
379    }
380}