Skip to main content

datex_core/values/cast/
try_from.rs

1//! Implements [TryFrom] for DATEX [CoreValue] and [Value] types. This allows to convert e.g. [CoreValue::Integer] to [Integer].
2use crate::{
3    traits::convert_value::ConvertValue,
4    types::{
5        entities::entity_type_definition::EntityTypeDefinition, r#type::Type,
6    },
7    utils::{goat::Goat, goat_mut::GoatMut},
8    values::{
9        core_value::{
10            CoreValue,
11            borrowed_core_value::{BorrowedCoreValue, BorrowedCoreValueMut},
12        },
13        core_value_with_classification::{
14            CoreValueWithClassification,
15            borrowed_core_value_with_classification::{
16                BorrowedCoreValueWithClassification,
17                BorrowedCoreValueWithClassificationMut,
18            },
19        },
20        core_values::{
21            boolean::Boolean,
22            callable::Callable,
23            decimal::{Decimal, typed_decimal::TypedDecimal},
24            endpoint::Endpoint,
25            instant::Instant,
26            integer::{Integer, typed_integer::TypedInteger},
27            list::List,
28            map::Map,
29            range::Range,
30            text::Text,
31        },
32        value::{
33            Value,
34            borrowed_value::{BorrowedValue, BorrowedValueMut},
35        },
36    },
37};
38
39/// Implements [TryFrom] for each [CoreValue] variant to its corresponding type.
40/// This allows to convert e.g. [CoreValue::Integer] to [Integer].
41/// This also allows to borrow or mutably borrow the corresponding type from a [CoreValue].
42/// Implementation for the try from core value methods is also done for [CoreValue::Native] branch.
43macro impl_convert_value($($variant:ident => $type:ty),* $(,)?) {
44    $(
45        impl ConvertValue for $type {
46            fn to_value(self) -> Value {
47                Value::Core(CoreValueWithClassification::new(CoreValue::$variant(self)))
48            }
49
50            fn try_from_value(value: Value) -> Result<Self, Value> {
51                match value {
52                    Value::Native(native) => {
53                        match native.try_into_value() {
54                            Ok(v) => Ok(v),
55                            Err(native) => Err(Value::Native(native)),
56                        }
57                    },
58                    Value::Core(CoreValueWithClassification {inner: CoreValue::$variant(v), ..}) => Ok(v),
59                    _ => Err(value),
60                }
61            }
62
63            fn try_borrow_from_value(value: &Value) -> Result<&$type, ()> {
64                match value {
65                    Value::Core(CoreValueWithClassification {inner: CoreValue::$variant(v), ..}) => Ok(v),
66                    Value::Native(native) => {
67                        native.try_as::<$type>().ok_or(())
68                    },
69                    _ => Err(()),
70                }
71            }
72
73            fn try_borrow_mut_from_value(value: &mut Value) -> Result<&mut $type, ()> {
74                match value {
75                    Value::Core(CoreValueWithClassification {inner: CoreValue::$variant(v), ..}) => Ok(v),
76                    Value::Native(native) => {
77                        native.try_as_mut::<$type>().ok_or(())
78                    },
79                    _ => Err(()),
80                }
81            }
82        }
83    )*
84}
85
86macro impl_try_from_core_value($($variant:ident => $type:ty),* $(,)?) {
87    $(
88        impl<'a> TryFrom<BorrowedValue<'a>> for Goat<'a, $type> {
89            type Error = BorrowedValue<'a>;
90            fn try_from(value: BorrowedValue<'a>) -> Result<Self, Self::Error> {
91                match value {
92                    // BorrowedCoreValue::$variant(v) => Ok(v),
93                    BorrowedValue::Core(BorrowedCoreValueWithClassification {
94                        inner: BorrowedCoreValue::$variant(v),
95                        ..
96                    }) => Ok(v),
97                    _ => Err(value),
98                }
99            }
100        }
101
102        impl<'a> TryFrom<BorrowedValueMut<'a>> for GoatMut<'a, $type> {
103            type Error = BorrowedValueMut<'a>;
104            fn try_from(value: BorrowedValueMut<'a>) -> Result<Self, Self::Error> {
105                match value {
106                    BorrowedValueMut::Core(
107                        BorrowedCoreValueWithClassificationMut {
108                            inner: BorrowedCoreValueMut::$variant(v),
109                            ..
110                        },
111                    ) => Ok(v),
112                    _ => Err(value),
113                }
114            }
115        }
116    )*
117}
118
119impl_try_from_core_value! {
120    Integer             => Integer,
121    TypedInteger        => TypedInteger,
122    Decimal             => Decimal,
123    TypedDecimal        => TypedDecimal,
124    Boolean             => Boolean,
125    Endpoint            => Endpoint,
126    List                => List,
127    Map                 => Map,
128    Type                => Type,
129    EntityTypeDefinition => EntityTypeDefinition,
130    Range               => Range,
131    Callable            => Callable,
132    Instant              => Instant,
133}
134
135impl_convert_value! {
136    Integer             => Integer,
137    TypedInteger        => TypedInteger,
138    Decimal             => Decimal,
139    TypedDecimal        => TypedDecimal,
140    Boolean             => Boolean,
141    Endpoint            => Endpoint,
142    List                => List,
143    Map                 => Map,
144    Text                => Text,
145    Type                => Type,
146    EntityTypeDefinition => EntityTypeDefinition,
147    Range               => Range,
148    Callable            => Callable,
149    Instant              => Instant,
150}
151
152#[cfg(test)]
153mod tests {
154    use core::assert_matches;
155
156    use crate::{
157        prelude::*,
158        traits::convert_value::ConvertValue,
159        values::{
160            core_value::CoreValue,
161            core_values::{
162                endpoint::Endpoint, integer::Integer, native::NativeCoreValue,
163                text::Text,
164            },
165            value::Value,
166        },
167    };
168
169    #[test]
170    fn try_from_value() {
171        let int_value = CoreValue::Integer(Integer::new(42)).to_value();
172        let int: Integer = int_value.try_into_value().unwrap();
173        assert_eq!(int, Integer::new(42));
174
175        let text_value = CoreValue::Text(Text::new("Hello, DATEX!")).to_value();
176        let text: Text = text_value.try_into_value().unwrap();
177        assert_eq!(text, Text::new("Hello, DATEX!"));
178    }
179
180    #[test]
181    fn try_from_core_value_wrong_type() {
182        let int_value = CoreValue::Integer(Integer::new(42)).to_value();
183        let result = int_value.try_into_value::<Text>();
184        assert_matches!(result, Err(_));
185    }
186
187    #[test]
188    fn try_from_core_value_ref() {
189        let int_value = CoreValue::Integer(Integer::new(42)).to_value();
190        let int_ref = int_value.try_as::<Integer>().unwrap();
191        assert_eq!(*int_ref, Integer::new(42));
192
193        let text_value = CoreValue::Text(Text::new("Hello, DATEX!")).to_value();
194        let text_ref: &Text = text_value.try_as().unwrap();
195        assert_eq!(*text_ref, Text::new("Hello, DATEX!"));
196    }
197
198    #[test]
199    fn try_from_core_value_mut_ref() {
200        let mut int_value = CoreValue::Integer(Integer::new(42)).to_value();
201        let int_mut_ref = int_value.try_as_mut::<Integer>().unwrap();
202        *int_mut_ref = Integer::new(100);
203        assert_eq!(*int_mut_ref, Integer::new(100));
204        assert_eq!(int_value, CoreValue::Integer(Integer::new(100)).to_value());
205    }
206
207    #[test]
208    fn try_into_value_value() {
209        let value = Value::from(CoreValue::Integer(Integer::new(42)));
210        let int: Integer = value.try_into_value().unwrap();
211        assert_eq!(int, Integer::new(42));
212    }
213
214    #[test]
215    fn try_into_value_native() {
216        let native_endpoint = Value::from(Endpoint::new("@test"));
217        let endpoint: Endpoint = native_endpoint.try_into_value().unwrap();
218        assert_eq!(endpoint.to_string(), "@test");
219    }
220    #[test]
221    fn try_borrow_from_core_value_native() {
222        let mut native_endpoint =
223            Value::Native(NativeCoreValue::new(Endpoint::new("@test")));
224        let endpoint_ref: &Endpoint =
225            Endpoint::try_borrow_from_value(&native_endpoint).unwrap();
226        assert_eq!(*endpoint_ref, Endpoint::new("@test"));
227
228        let endpoint_mut_ref: &mut Endpoint =
229            Endpoint::try_borrow_mut_from_value(&mut native_endpoint).unwrap();
230        *endpoint_mut_ref = Endpoint::new("@test2");
231        assert_eq!(*endpoint_mut_ref, Endpoint::new("@test2"));
232
233        assert_eq!(
234            native_endpoint,
235            Value::Native(NativeCoreValue::new(Endpoint::new("@test2")))
236        );
237    }
238}