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        errors::{
10            UnexpectedImmutableReferenceError,
11            UnexpectedSharedContainerOwnershipError,
12        },
13        traits::_ExposeRcInternal,
14    },
15    values::value_container::ValueContainer,
16};
17pub mod identity;
18pub(crate) mod to_instructions;
19use crate::{
20    prelude::*,
21    runtime::cache::shared_references_cache::SharedReferencesCache,
22    shared_values::{
23        ReferenceMutability,
24        base_shared_value_container::observers::{
25            ObserveOptions, Observer, ObserverCallback, ObserverError,
26            ObserverId,
27        },
28        collapsed_container_value::{
29            CollapsedContainerValue, CollapsedContainerValueMut,
30        },
31        shared_mut::SharedMut,
32        traits::SharedContainerCommon,
33    },
34    traits::convert_value_container::ConvertValueContainer,
35    types::type_definition::TypeDefinition,
36    value_updates::update_handler::{
37        InternalMutabilityUpdateHandler, UpdateCallbackData,
38    },
39    values::{core_value::CoreValue, core_values::native::DatexNative},
40};
41use alloc::rc::Rc;
42use core::{
43    cell::{Ref, RefCell, RefMut},
44    fmt::{Debug, Display, Formatter},
45    mem,
46    ops::Deref,
47};
48
49pub mod apply;
50pub mod serde_dif;
51/// Top-level wrapper for any owned or referenced shared container,
52/// which can either be an owned shared container or a reference to a shared container.
53pub enum SharedContainer {
54    /// An owned shared container (`shared X`). This is always points to a [SharedContainerInner::EndpointOwned]
55    Owned(OwnedSharedContainer),
56    /// A referenced shared container (`'shared X` or `'mut shared X`).
57    /// This can point to either a [SharedContainerInner::EndpointOwned] or a [SharedContainerInner::External]
58    Referenced(ReferencedSharedContainer),
59}
60
61impl Debug for SharedContainer {
62    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
63        // recursive reference
64        if self.is_borrowed() {
65            f.write_str("(...)")
66        } else {
67            match self {
68                SharedContainer::Owned(owned) => {
69                    f.debug_tuple("SharedContainer").field(owned).finish()
70                }
71                SharedContainer::Referenced(reference) => {
72                    f.debug_tuple("SharedContainer").field(reference).finish()
73                }
74            }
75        }
76    }
77}
78
79impl SharedContainer {
80    /// Creates a new owned [SharedContainer] with an initial [ValueContainer],
81    /// a [SharedContainerMutability], and a [SelfOwnedPointerAddressProvider].
82    ///
83    /// The allowed type is inferred from the value_container's allowed type.
84    pub fn new_owned_with_inferred_allowed_type<T: Into<ValueContainer>>(
85        value_container: T,
86        mutability: SharedContainerMutability,
87        address_provider: &mut SelfOwnedPointerAddressProvider,
88    ) -> Self {
89        SharedContainer::Owned(
90            OwnedSharedContainer::new_with_inferred_allowed_type(
91                value_container,
92                mutability,
93                address_provider,
94            ),
95        )
96    }
97
98    /// Creates a new owned [SharedContainer] containing an initial [DatexNative] value.
99    /// The allowed type is the type of the [DatexNative].
100    pub fn new_native<T: DatexNative>(
101        value: T,
102        mutability: SharedContainerMutability,
103        address_provider: &mut SelfOwnedPointerAddressProvider,
104        cache: &mut SharedReferencesCache,
105    ) -> Self {
106        SharedContainer::Owned(OwnedSharedContainer::new_native(
107            value,
108            mutability,
109            address_provider,
110            cache,
111        ))
112    }
113
114    /// Creates a new owned [SharedContainer] with an initial [ValueContainer],
115    /// a [SharedContainerMutability], and a [SelfOwnedPointerAddress].
116    ///
117    /// The allowed type is inferred from the value_container's allowed type.
118    /// # Safety
119    /// The caller must ensure that the address is not used anywhere else.
120    pub unsafe fn new_owned_with_inferred_allowed_type_unsafe<
121        T: Into<ValueContainer>,
122    >(
123        value_container: T,
124        mutability: SharedContainerMutability,
125        address: SelfOwnedPointerAddress,
126    ) -> Self {
127        SharedContainer::Owned(unsafe {
128            OwnedSharedContainer::new_with_inferred_allowed_type_unsafe(
129                value_container.into(),
130                mutability,
131                address,
132            )
133        })
134    }
135
136    /// Ensures that the shared container is mutable and returns it.
137    /// Returns an ObserverError if the reference is immutable (or a type container).
138    fn ensure_mutable_container(&self) -> Result<(), ObserverError> {
139        if self.container_mutability() != SharedContainerMutability::Mutable {
140            return Err(ObserverError::ImmutableValue);
141        }
142        Ok(())
143    }
144
145    /// Adds an observer to this shared container that will be notified on value changes.
146    pub fn observe(
147        &self,
148        observer: Observer,
149    ) -> Result<ObserverId, ObserverError> {
150        self.ensure_mutable_container()?;
151        let res = self.observer_data_mut().observe(observer)?;
152        self.ensure_local_nested_observe_callbacks();
153
154        Ok(res)
155    }
156
157    pub fn unobserve(
158        &self,
159        observer_id: ObserverId,
160    ) -> Result<(), ObserverError> {
161        self.ensure_mutable_container()?;
162        self.observer_data_mut().unobserve(observer_id)?;
163
164        // also disable local nested observe callbacks if there are no more observers registered
165        if !self.observer_data().has_observers() {
166            self.disable_local_nested_observe_callbacks();
167        }
168
169        Ok(())
170    }
171
172    /// Updates the options for an existing observer by its ID.
173    /// Returns an error if the observer ID is not found or the reference is immutable.
174    pub fn update_observer_options(
175        &self,
176        observer_id: ObserverId,
177        options: ObserveOptions,
178    ) -> Result<(), ObserverError> {
179        self.ensure_mutable_container()?;
180        self.observer_data_mut()
181            .update_observer_options(observer_id, options)
182    }
183
184    // Enables observe callbacks for the inner local value if not yet enabled
185    fn ensure_local_nested_observe_callbacks(&self) {
186        let enabled = if !self.observer_data().get_local_observers_enabled()
187            && let ValueContainer::Local(local_value) =
188                self.base_shared_container_mut().value_container_mut()
189        {
190            let self_clone = self.clone();
191
192            let callback: ObserverCallback = Rc::new(move |update| {
193                // TODO: check if not already borrowed?
194                self_clone.observer_data_mut().call_observers(update);
195            });
196            local_value.set_update_callback_data(Some(UpdateCallbackData {
197                callback,
198                path: vec![],
199            }));
200            true
201        } else {
202            false
203        };
204
205        if enabled {
206            self.observer_data_mut().set_local_observers_enabled(true);
207        }
208    }
209
210    fn disable_local_nested_observe_callbacks(&self) {
211        let mut base = self.base_shared_container_mut();
212        if self.observer_data().get_local_observers_enabled()
213            && let ValueContainer::Local(local_value) =
214                base.value_container_mut()
215        {
216            local_value.set_update_callback_data(None);
217        }
218        self.observer_data_mut().set_local_observers_enabled(false);
219    }
220
221    /// Gets the current actual [TypeDefinition] of the collapsed inner [Value]
222    pub fn actual_type(&self) -> TypeDefinition {
223        let value = self.collapsed_value();
224        value.borrow().actual_type()
225    }
226
227    pub fn collapsed_value(&self) -> CollapsedContainerValue<'_> {
228        CollapsedContainerValue::new_shared(self.get_collapsed_rc())
229    }
230
231    pub fn collapsed_value_mut(&self) -> CollapsedContainerValueMut<'_> {
232        CollapsedContainerValueMut::new_shared(self.get_collapsed_rc())
233    }
234
235    /// Returns the Rc<RefCell<SharedContainerInner>> of the most inner local value of the shared container.
236    fn get_collapsed_rc(&self) -> Rc<RefCell<SharedContainerInner>> {
237        // TODO: no clone of RC?
238        // collapse nested direct shared children until most inner local value is found
239        let mut inner_rc = self.get_rc_internal().clone();
240
241        loop {
242            let next_rc = {
243                let borrowed = inner_rc.borrow();
244
245                match borrowed.base_shared_container().value_container() {
246                    ValueContainer::Shared(shared) => {
247                        Some(shared.get_rc_internal().clone())
248                    }
249                    _ => None,
250                }
251            };
252
253            match next_rc {
254                Some(rc) => inner_rc = rc,
255                None => break,
256            }
257        }
258
259        inner_rc
260    }
261
262    pub fn pointer_address(&self) -> PointerAddress {
263        match self {
264            SharedContainer::Owned(owned) => {
265                PointerAddress::SelfOwned(owned.pointer_address().clone())
266            }
267            SharedContainer::Referenced(referenced) => {
268                referenced.pointer_address()
269            }
270        }
271    }
272
273    /// Returns true if the shared container has a self owned pointer address
274    pub fn is_self_owned(&self) -> bool {
275        match self {
276            SharedContainer::Owned(_owned) => true,
277            SharedContainer::Referenced(referenced) => {
278                matches!(
279                    referenced.inner().deref(),
280                    SharedContainerInner::EndpointOwned(_)
281                )
282            }
283        }
284    }
285
286    /// Creates a new immutable [ReferencedSharedContainer] pointing to the same inner value as self.
287    pub fn derive_immutable_reference(&self) -> ReferencedSharedContainer {
288        match self {
289            SharedContainer::Owned(owned) => owned.derive_immutable_reference(),
290            SharedContainer::Referenced(referenced) => {
291                referenced.derive_immutable_reference()
292            }
293        }
294    }
295    /// Tries to create a new mutable or immutable [ReferencedSharedContainer] pointing to the same inner value as this [OwnedSharedContainer].
296    /// Returns an [Err] if the requested mutability is [ReferenceMutability::Mutable],
297    /// but the current reference_mutability is [ReferenceMutability::Immutable] or the container itself is not mutable
298    pub fn try_derive_reference_with_mutability(
299        &self,
300        mutability: ReferenceMutability,
301    ) -> Result<ReferencedSharedContainer, UnexpectedImmutableReferenceError>
302    {
303        match mutability {
304            ReferenceMutability::Immutable => {
305                Ok(self.derive_immutable_reference())
306            }
307            ReferenceMutability::Mutable => self.try_derive_mutable_reference(),
308        }
309    }
310
311    /// Tries to create a new mutable [ReferencedSharedContainer] pointing to the same inner value as this [OwnedSharedContainer].
312    /// Returns an [Err] if the current reference_mutability is [ReferenceMutability::Immutable] or the container itself is not mutable
313    pub fn try_derive_mutable_reference(
314        &self,
315    ) -> Result<ReferencedSharedContainer, UnexpectedImmutableReferenceError>
316    {
317        match self {
318            SharedContainer::Owned(owned) => owned
319                .try_derive_mutable_reference()
320                .map_err(|_| UnexpectedImmutableReferenceError),
321            SharedContainer::Referenced(referenced) => {
322                referenced.try_derive_mutable_reference()
323            }
324        }
325    }
326
327    /// Returns the owned shared container if it is owned, otherwise returns an error.
328    pub fn try_get_owned(
329        &self,
330    ) -> Result<&OwnedSharedContainer, UnexpectedSharedContainerOwnershipError>
331    {
332        match self {
333            SharedContainer::Owned(owned) => Ok(owned),
334            SharedContainer::Referenced(reference) => {
335                Err(UnexpectedSharedContainerOwnershipError {
336                    actual: SharedContainerOwnership::Referenced(
337                        reference.reference_mutability(),
338                    ),
339                    expected: SharedContainerOwnership::Owned,
340                })
341            }
342        }
343    }
344
345    /// Clones the shared container as a mutable reference if possible, otherwise as an immutable reference
346    pub fn derive_reference_with_max_mutability(
347        &self,
348    ) -> ReferencedSharedContainer {
349        self.try_derive_mutable_reference()
350            .unwrap_or_else(|_| self.derive_immutable_reference())
351    }
352
353    /// Downgrades an owned shared container to a referenced shared container.
354    /// If the shared container is already a referenced shared container, it will just be returned.
355    /// If the shared container is owned, it will be replaced with a new referenced shared container pointing to the same inner value
356    /// and the original owned shared container will be returned.
357    /// Also sets the move indicator on the original owned shared container, so that we know it should be treated as moved.
358    pub fn downgrade_to_reference(&mut self) -> SharedContainer {
359        match self {
360            SharedContainer::Owned(_) => {
361                // replace previous with null value
362                // FIXME: find a more efficient way to do this enum variant swap
363                let previous = mem::replace(&mut *self, unsafe {
364                    SharedContainer::new_owned_with_inferred_allowed_type_unsafe(
365                        CoreValue::Null,
366                        SharedContainerMutability::Immutable,
367                        SelfOwnedPointerAddress::new([0; 5]),
368                    )
369                });
370
371                // create a new referenced shared container and assign to self
372                *self = previous.clone_with_move_indicator_if_owned();
373
374                // return original, potentially owned shared container
375                previous
376            }
377            SharedContainer::Referenced(referenced) => {
378                SharedContainer::Referenced(referenced.clone())
379            }
380        }
381    }
382
383    /// Tries to upgrade an inner [ReferencedSharedContainer] to an [OwnedSharedContainer].
384    /// If the container is already an [OwnedSharedContainer], it will be returned as is.
385    /// If the move indicator is set, the inner value is moved into a new [OwnedSharedContainer] and returned.
386    /// If the move indicator is not set, an [Err] is returned with the original [ReferencedSharedContainer].
387    /// Panics if the move indicator is set but the address is not a [SelfOwnedPointerAddress].
388    ///
389    /// # Safety
390    /// The caller must ensure that no other [OwnedSharedContainer] for the same inner value exists
391    /// if move_indicator of the [ReferencedSharedContainer] is set.
392    pub unsafe fn try_upgrade_to_owned(
393        self,
394    ) -> Result<OwnedSharedContainer, ReferencedSharedContainer> {
395        match self {
396            SharedContainer::Referenced(referenced_container) => unsafe {
397                referenced_container.try_upgrade_to_owned()
398            },
399            SharedContainer::Owned(owned_container) => Ok(owned_container),
400        }
401    }
402
403    /// Clones the shared container with the move indicator if it is an [OwnedSharedContainer],
404    /// otherwise as a normal reference
405    pub fn clone_with_move_indicator_if_owned(&self) -> SharedContainer {
406        SharedContainer::Referenced(match self {
407            SharedContainer::Owned(owned) => owned.clone_with_move_indicator(),
408            SharedContainer::Referenced(referenced) => referenced.clone(),
409        })
410    }
411
412    /// Returns true if the shared container is an [OwnedSharedContainer] or a [ReferencedSharedContainer] that is marked as moved.
413    pub fn treat_as_move(&self) -> bool {
414        match self {
415            SharedContainer::Owned(_owned) => true,
416            SharedContainer::Referenced(referenced) => {
417                referenced.treat_as_move()
418            }
419        }
420    }
421
422    pub fn to_string_omit_content(&self) -> String {
423        match self {
424            SharedContainer::Owned(owned) => owned.to_string_omit_content(),
425            SharedContainer::Referenced(referenced) => {
426                referenced.to_string_omit_content()
427            }
428        }
429    }
430
431    /// Tries to get an immutable reference to the value as a specified type.
432    /// Does not perform any type conversion.
433    /// This only works for local values, not for shared values.
434    pub fn try_as<T>(&self) -> Option<Ref<'_, T>>
435    where
436        T: ConvertValueContainer,
437    {
438        Ref::filter_map(self.value_container(), |value| value.try_as::<T>())
439            .ok()
440    }
441
442    /// Tries to get a mutable reference to the value as a specified type.
443    /// Does not perform any type conversion.
444    /// This only works for local values, not for shared values.
445    pub fn try_as_mut<T>(&self) -> Option<SharedMut<'_, T>>
446    where
447        T: ConvertValueContainer,
448    {
449        RefMut::filter_map(self.value_container_mut(), |value| {
450            value.try_as_mut::<T>()
451        })
452        .ok()
453        .map(|v| SharedMut::new(v, self))
454    }
455
456    /// This method is called when a borrow of the inner shared container is dropped.
457    pub fn notify_borrow_dropped(&self) {
458        // TODO: this could be used in the future to trigger queued updates only after a borrow was dropped
459    }
460
461    /// Marks the shared container as uninitialized.
462    #[allow(unused)]
463    pub(crate) fn mark_uninitialized(&mut self) {
464        match self {
465            SharedContainer::Owned(owned) => owned.mark_uninitialized(),
466            SharedContainer::Referenced(referenced) => {
467                referenced.mark_uninitialized()
468            }
469        }
470    }
471
472    /// Unmarks the shared container as uninitialized.
473    pub(crate) fn unset_uninitialized(&mut self) {
474        match self {
475            SharedContainer::Owned(owned) => owned.unset_uninitialized(),
476            SharedContainer::Referenced(referenced) => {
477                referenced.unset_uninitialized()
478            }
479        }
480    }
481
482    pub fn mark_debug(&self, is_debug: bool) {
483        self.base_shared_container_mut().mark_debug(is_debug);
484    }
485
486    pub fn is_debug(&self) -> bool {
487        self.base_shared_container().is_debug()
488    }
489}
490
491/// Custom clone implementation for [SharedContainer].
492/// A [SharedContainer::Owned] cannot be cloned as is, only a new reference can be created
493/// A [SharedContainer::Referenced] can be cloned normally
494impl Clone for SharedContainer {
495    fn clone(&self) -> Self {
496        match self {
497            // An owned container cannot be cloned, only a new reference can be created
498            SharedContainer::Owned(owned) => {
499                SharedContainer::Referenced(owned.derive_with_max_mutability())
500            }
501            // A referenced container can be cloned
502            SharedContainer::Referenced(referenced) => {
503                SharedContainer::Referenced(referenced.clone())
504            }
505        }
506    }
507}
508
509// TODO: use impl_display_for_datex_value
510impl Display for SharedContainer {
511    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
512        match self {
513            SharedContainer::Owned(owned) => write!(f, "{}", owned),
514            SharedContainer::Referenced(referenced) => {
515                write!(f, "{}", referenced)
516            }
517        }
518    }
519}
520
521pub mod clone_unsafe;
522mod common;
523mod convert_value_container;
524pub mod equality;
525pub mod get_datex_type;
526pub mod update_handler;
527
528impl From<OwnedSharedContainer> for SharedContainer {
529    fn from(value: OwnedSharedContainer) -> Self {
530        SharedContainer::Owned(value)
531    }
532}
533
534impl From<ReferencedSharedContainer> for SharedContainer {
535    fn from(value: ReferencedSharedContainer) -> Self {
536        SharedContainer::Referenced(value)
537    }
538}
539
540impl _ExposeRcInternal for SharedContainer {
541    type Shared = SharedContainerInner;
542    fn get_rc_internal(&self) -> &Rc<RefCell<Self::Shared>> {
543        match self {
544            SharedContainer::Owned(owned) => owned.get_rc_internal(),
545            SharedContainer::Referenced(referenced) => {
546                referenced.get_rc_internal()
547            }
548        }
549    }
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555    use core::assert_matches;
556
557    #[test]
558    fn immutable_reference_observe_fails() {
559        let address_provider = &mut SelfOwnedPointerAddressProvider::default();
560        let shared = SharedContainer::new_owned_with_inferred_allowed_type(
561            42,
562            SharedContainerMutability::Immutable,
563            address_provider,
564        );
565        assert_matches!(
566            shared.observe(Observer::new(|_| {})),
567            Err(ObserverError::ImmutableValue)
568        );
569
570        let r = SharedContainer::new_owned_with_inferred_allowed_type(
571            42,
572            SharedContainerMutability::Mutable,
573            address_provider,
574        );
575        assert_matches!(r.observe(Observer::new(|_| {})), Ok(_));
576    }
577}