Skip to main content

datex_core/values/value_container/
mod.rs

1//! This module contains the implementation of the [ValueContainer] enum, which represents a container for values in the DATEX type system.
2//! A [ValueContainer] can either be a local value, which directly contains a [Value], or a shared value, which contains a reference to a [SharedContainer].
3use crate::values::value_container::value_key::BorrowedValueKey;
4pub mod equality;
5pub mod identity;
6use core::result::Result;
7pub mod serde_dif;
8use super::value::Value;
9use crate::{
10    prelude::*,
11    shared_values::{SharedContainer, errors::AccessError},
12    types::{
13        r#type::Type,
14        type_definition::TypeDefinition,
15        type_definition_with_metadata::{
16            TypeDefinitionWithMetadata, TypeMetadata,
17        },
18    },
19    values::core_value::CoreValue,
20};
21
22pub mod apply;
23pub mod ops;
24pub mod update_handler;
25pub mod value_key;
26use core::{
27    fmt::Display,
28    hash::{Hash, Hasher},
29    ops::FnOnce,
30};
31pub mod datex_proxy;
32pub mod error;
33
34#[derive(Debug, Eq, Clone)]
35pub enum ValueContainer {
36    Local(Value),
37    Shared(SharedContainer),
38}
39
40impl ValueContainer {
41    /// Creates a new [ValueContainer::Local] from a [Value]
42    pub fn local(value: impl Into<Value>) -> Self {
43        ValueContainer::Local(value.into())
44    }
45
46    /// Calls a fn with a reference to the current inner collapsed value of the  container
47    pub fn with_collapsed_value<R, F: FnOnce(&Value) -> R>(&self, f: F) -> R {
48        match self {
49            ValueContainer::Local(value) => f(value),
50            ValueContainer::Shared(shared) => shared.with_collapsed_value(f),
51        }
52    }
53
54    /// Calls a fn with a mutable reference to the current inner collapsed value of the container
55    pub(crate) fn with_collapsed_value_mut<R, F: FnOnce(&mut Value) -> R>(
56        &mut self,
57        f: F,
58    ) -> R {
59        match self {
60            ValueContainer::Local(value) => f(value),
61            ValueContainer::Shared(shared) => {
62                shared.with_collapsed_value_mut(f)
63            }
64        }
65    }
66
67    /// Gets a cloned, collapsed inner value.
68    /// Use [ValueContainer::with_collapsed_value] instead whenever possible
69    /// or match the [ValueContainer]
70    pub fn get_cloned_value(&self) -> Value {
71        self.with_collapsed_value(|value| value.clone())
72    }
73
74    /// Tries to get an immutable reference to the value as a specified type.
75    /// Does not perform any type conversion.
76    /// This only works for local values, not for shared values.
77    pub fn try_as<'a, T>(&'a self) -> Option<&'a T>
78    where
79        &'a T: TryFrom<&'a CoreValue>,
80    {
81        match self {
82            ValueContainer::Local(value) => value.inner.try_as(),
83            ValueContainer::Shared(_) => None,
84        }
85    }
86
87    /// Tries to get a mutable reference to the value as a specified type.
88    /// Does not perform any type conversion.
89    /// This only works for local values, not for shared values.
90    pub fn try_as_mut<'a, T>(&'a mut self) -> Option<&'a mut T>
91    where
92        &'a mut T: TryFrom<&'a mut CoreValue>,
93    {
94        match self {
95            ValueContainer::Local(value) => value.inner.try_as_mut(),
96            ValueContainer::Shared(_) => None,
97        }
98    }
99
100    /// Tries to get the current collapsed value as a specified type.
101    /// Does not perform any type conversion.
102    /// Runs the provided closure with a reference to the typed value if the conversion was successful, otherwise returns None.
103    pub fn try_with<T, R, F>(&self, f: F) -> Option<R>
104    where
105        F: for<'a> FnOnce(&'a T) -> R,
106        for<'a> &'a T: TryFrom<&'a CoreValue>,
107    {
108        self.with_collapsed_value(|value| value.inner.try_as().map(f))
109    }
110
111    /// Tries to get the current collapsed value as a specified type.
112    /// Does not perform any type conversion.
113    /// This only works for local values, not for shared values.
114    pub fn try_into_value<T>(self) -> Option<T>
115    where
116        T: TryFrom<CoreValue>,
117    {
118        match self {
119            ValueContainer::Local(value) => value.inner.try_into().ok(),
120            ValueContainer::Shared(_) => None,
121        }
122    }
123
124    /// Performs a clone used by the "clone" command
125    /// Local values are just cloned normally
126    /// For shared value, the inner value container is cloned (shared x -> x)
127    pub fn get_cloned(&self) -> ValueContainer {
128        match self {
129            ValueContainer::Local(value) => {
130                ValueContainer::Local(value.clone())
131            }
132            ValueContainer::Shared(shared) => shared.value_container().clone(),
133        }
134    }
135
136    /// Returns the actual type of the contained value, resolving shared values if necessary.
137    pub fn actual_type(&self) -> TypeDefinition {
138        match self {
139            ValueContainer::Local(local) => local.actual_type().clone(),
140            ValueContainer::Shared(shared) => shared.actual_type().clone(),
141        }
142    }
143
144    /// Returns the actual type that describes the value container (e.g. integer or 'mut shared mut integer).
145    pub fn actual_container_type(&self) -> TypeDefinitionWithMetadata {
146        match self {
147            ValueContainer::Local(value) => TypeDefinitionWithMetadata {
148                definition: value.actual_type(),
149                metadata: TypeMetadata::default(),
150                reference_name: None,
151            },
152            ValueContainer::Shared(shared) => {
153                let inner_type =
154                    shared.value_container().actual_container_type();
155                TypeDefinitionWithMetadata {
156                    definition: TypeDefinition::Nested(Box::new(Type::from(
157                        inner_type,
158                    ))),
159                    metadata: TypeMetadata::Shared {
160                        mutability: shared.container_mutability(),
161                        ownership: shared.ownership(),
162                    },
163                    reference_name: None,
164                }
165            }
166        }
167    }
168
169    /// For local values, returns the actual type of the value container
170    /// For shared values, returns the allowed type of the value container
171    pub fn allowed_or_actual_type(&self) -> TypeDefinition {
172        match self {
173            ValueContainer::Local(value) => value.actual_type(),
174            ValueContainer::Shared(shared) => shared.allowed_type().clone(),
175        }
176    }
177
178    /// Returns the contained SharedContainer if it is a SharedContainer, otherwise returns None.
179    pub fn maybe_shared(&self) -> Option<&SharedContainer> {
180        if let ValueContainer::Shared(shared) = self {
181            Some(shared)
182        } else {
183            None
184        }
185    }
186
187    /// Runs a closure with the contained SharedContainer if it is a SharedContainer, otherwise returns None.
188    pub fn with_maybe_shared<F, R>(&self, f: F) -> Option<R>
189    where
190        F: FnOnce(&SharedContainer) -> R,
191    {
192        if let ValueContainer::Shared(shared) = self {
193            Some(f(shared))
194        } else {
195            None
196        }
197    }
198
199    /// Returns a reference to the contained SharedContainer, panics if it is not a SharedContainer.
200    pub fn shared_unchecked(&self) -> &SharedContainer {
201        match self {
202            ValueContainer::Shared(shared) => shared,
203            _ => {
204                core::panic!("Cannot convert ValueContainer to SharedContainer")
205            }
206        }
207    }
208
209    pub fn try_get_property<'a>(
210        &self,
211        key: impl Into<BorrowedValueKey<'a>>,
212    ) -> Result<ValueContainer, AccessError> {
213        match self {
214            ValueContainer::Local(value) => value.try_get_property(key),
215            ValueContainer::Shared(reference) => {
216                reference.try_get_property(key)
217            }
218        }
219    }
220}
221
222impl<T: Into<Value>> From<T> for ValueContainer {
223    fn from(value: T) -> Self {
224        ValueContainer::Local(value.into())
225    }
226}
227
228impl<'a> From<BorrowedValueKey<'a>> for ValueContainer {
229    fn from(value_key: BorrowedValueKey) -> Self {
230        match value_key {
231            BorrowedValueKey::Text(text) => {
232                ValueContainer::Local(text.into_owned().into())
233            }
234            BorrowedValueKey::Index(index) => {
235                ValueContainer::Local(index.into())
236            }
237            BorrowedValueKey::Value(value_container) => {
238                value_container.into_owned()
239            }
240        }
241    }
242}
243
244impl Hash for ValueContainer {
245    fn hash<H: Hasher>(&self, state: &mut H) {
246        match self {
247            ValueContainer::Local(value) => value.hash(state),
248            ValueContainer::Shared(pointer) => pointer.hash(state),
249        }
250    }
251}
252
253impl Display for ValueContainer {
254    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
255        match self {
256            ValueContainer::Local(value) => core::write!(f, "{value}"),
257            // TODO #118: only simple temporary way to distinguish between Value and Pointer
258            ValueContainer::Shared(reference) => reference
259                .with_collapsed_value_mut(|reference| {
260                    write!(f, "&({})", reference)
261                }),
262        }
263    }
264}