Skip to main content

datex_core/values/rust_values/
mod.rs

1//! Implements [TryFrom] and [TryInto] for Rust native types to and from DATEX [CoreValue], [Value] and [ValueContainer] types.
2//! This allows to convert [u8] into DATEX [Value] and [ValueContainer] and allows to convert [CoreValue], [Value] and [ValueContainer] into [u8].
3mod bool;
4mod r#box;
5mod duration;
6mod floats;
7mod index_map;
8mod integers;
9mod option;
10mod string;
11mod vec;
12
13use crate::{
14    libs::core::type_id::{CoreLibBaseTypeId, CoreLibVariantTypeId},
15    prelude::*,
16    traits::{
17        convert_parts::HasPartsKind,
18        convert_value_container::ConvertValueContainer, iter_parts::IterParts,
19        local_child_path_resolver::LocalChildPathResolver,
20    },
21    types::r#type::Type,
22    values::{
23        core_value::CoreValue,
24        core_values::{native::DatexNative, text::Text},
25        value::Value,
26        value_container::ValueContainer,
27    },
28};
29use core::any::Any;
30
31use crate::{
32    libs::core::type_id::CoreLibTypeId,
33    runtime::cache::shared_references_cache::SharedReferencesCache,
34    traits::{
35        classification::Classification,
36        convert_parts::{FromParts, IntoParts},
37        datex_native_only_structural::DatexNativeOnlyStructural,
38        datex_native_structural::DatexNativeStructural,
39        get_core_lib_type_id::GetCoreLibTypeId,
40        get_datex_type::GetDatexType,
41    },
42    types::type_definition::TypeDefinition,
43    value_updates::update_handler::{
44        UpdateCallbackDataAccess, UpdateHandlerImpl,
45    },
46    values::core_values::{
47        decimal::typed_decimal::DecimalTypeVariant,
48        integer::typed_integer::IntegerTypeVariant, native::DatexNativeOps,
49    },
50};
51/// Implements [DatexNative] and associated traits for Rust core types.
52macro_rules! implement_rust_native_traits {
53    ($type:ty, $dx_type:expr, {$($core_match:tt)*}, {$($core_ref_match:tt)*}) => {
54        impl DatexNative for $type {
55            fn as_any(&self) -> &dyn Any {
56                self
57            }
58
59            fn as_any_mut(&mut self) -> &mut dyn Any {
60                self
61            }
62        }
63        // impl DatexNativeOps for $type {}
64
65        impl Classification for $type {}
66        impl LocalChildPathResolver for $type {}
67        impl UpdateHandlerImpl for $type {}
68        impl UpdateCallbackDataAccess for $type {}
69        impl IterParts for $type {}
70
71        impl FromParts for $type {
72            fn try_from_single_value_with_tag(
73                value: ValueContainer,
74                _tag: Option<&str>,
75            ) -> Result<Self, ()>
76            where
77                Self: Sized,
78            {
79                Self::try_from_value_container(value).map_err(|_| ())
80            }
81        }
82        impl IntoParts for $type {
83            fn try_into_single_value<'a>(
84                self: Box<Self>,
85            ) -> Result<ValueContainer, ()>
86            where
87                Self: 'a,
88            {
89                Ok(self.to_value_container())
90            }
91        }
92        impl HasPartsKind for $type {}
93
94        impl DatexNativeStructural for $type {}
95        impl DatexNativeOnlyStructural for $type {}
96
97        impl GetCoreLibTypeId for $type {
98            fn core_lib_type_id(&self) -> CoreLibTypeId {
99                $dx_type.into()
100            }
101        }
102
103        impl GetDatexType for $type {
104            fn datex_type(_cache: &mut SharedReferencesCache) -> Type {
105                Type::Definition(
106                    TypeDefinition::CoreType($dx_type.into()).into(),
107                )
108            }
109        }
110    };
111}
112implement_rust_native_traits!(
113    bool,
114    CoreLibBaseTypeId::Boolean,
115    {
116        CoreValue::Boolean(Boolean(value)) => Ok(value),
117    },
118    {
119        CoreValue::Boolean(Boolean(value)) => Ok(value),
120    }
121);
122
123implement_rust_native_traits!(
124    u8,
125    CoreLibVariantTypeId::Integer(IntegerTypeVariant::U8),
126    {
127        CoreValue::TypedInteger(TypedInteger::U8(value)) => Ok(value),
128        CoreValue::TypedInteger(value) => value.to_u8().ok_or_else(|| ()),
129        CoreValue::TypedDecimal(value) => value.to_u8().ok_or_else(|| ()),
130    },
131    {
132        CoreValue::TypedInteger(TypedInteger::U8(value)) => Ok(value),
133    }
134);
135
136implement_rust_native_traits!(
137    u16,
138    CoreLibVariantTypeId::Integer(IntegerTypeVariant::U16),
139    {
140        CoreValue::TypedInteger(TypedInteger::U16(value)) => Ok(value),
141        CoreValue::TypedInteger(value) => value.to_u16().ok_or_else(|| ()),
142        CoreValue::TypedDecimal(value) => value.to_u16().ok_or_else(|| ()),
143    },
144    {
145        CoreValue::TypedInteger(TypedInteger::U16(value)) => Ok(value),
146    }
147);
148implement_rust_native_traits!(
149    u32,
150    CoreLibVariantTypeId::Integer(IntegerTypeVariant::U32),
151    {
152        CoreValue::TypedInteger(TypedInteger::U32(value)) => Ok(value),
153        CoreValue::TypedInteger(value) => value.to_u32().ok_or_else(|| ()),
154        CoreValue::TypedDecimal(value) => value.to_u32().ok_or_else(|| ()),
155    },
156    {
157        CoreValue::TypedInteger(TypedInteger::U32(value)) => Ok(value),
158    }
159);
160implement_rust_native_traits!(
161    u64,
162    CoreLibVariantTypeId::Integer(IntegerTypeVariant::U64),
163    {
164        CoreValue::TypedInteger(TypedInteger::U64(value)) => Ok(value),
165        CoreValue::TypedInteger(value) => value.to_u64().ok_or_else(|| ()),
166        CoreValue::TypedDecimal(value) => value.to_u64().ok_or_else(|| ()),
167    },
168    {
169        CoreValue::TypedInteger(TypedInteger::U64(value)) => Ok(value),
170    }
171);
172implement_rust_native_traits!(
173    u128,
174    CoreLibVariantTypeId::Integer(IntegerTypeVariant::U128),
175    {
176        CoreValue::TypedInteger(TypedInteger::U128(value)) => Ok(value),
177        CoreValue::TypedInteger(value) => value.to_u128().ok_or_else(|| ()),
178        CoreValue::TypedDecimal(value) => value.to_u128().ok_or_else(|| ()),
179    },
180    {
181        CoreValue::TypedInteger(TypedInteger::U128(value)) => Ok(value),
182    }
183);
184
185// usize depending on platform
186#[cfg(target_pointer_width = "32")]
187implement_rust_native_traits!(
188    usize,
189    CoreLibVariantTypeId::Integer(IntegerTypeVariant::U32),
190    {
191        CoreValue::TypedInteger(TypedInteger::U32(value)) => Ok(value as usize),
192        CoreValue::TypedInteger(value) => value.to_u32().map(|v| v as usize).ok_or_else(|| ()),
193        CoreValue::TypedDecimal(value) => value.to_u32().map(|v| v as usize).ok_or_else(|| ()),
194    },
195    {}
196);
197#[cfg(target_pointer_width = "64")]
198implement_rust_native_traits!(
199    usize,
200    CoreLibVariantTypeId::Integer(IntegerTypeVariant::U64),
201    {
202        CoreValue::TypedInteger(TypedInteger::U64(value)) => Ok(value as usize),
203        CoreValue::TypedInteger(value) => value.to_u64().map(|v| v as usize).ok_or_else(|| ()),
204        CoreValue::TypedDecimal(value) => value.to_u64().map(|v| v as usize).ok_or_else(|| ()),
205    },
206    {}
207);
208
209implement_rust_native_traits!(
210    i8,
211    CoreLibVariantTypeId::Integer(IntegerTypeVariant::I8),
212    {
213        CoreValue::TypedInteger(TypedInteger::I8(value)) => Ok(value),
214        CoreValue::TypedInteger(value) => value.to_i8().ok_or_else(|| ()),
215        CoreValue::TypedDecimal(value) => value.to_i8().ok_or_else(|| ()),
216    },
217    {
218        CoreValue::TypedInteger(TypedInteger::I8(value)) => Ok(value),
219    }
220);
221implement_rust_native_traits!(
222    i16,
223    CoreLibVariantTypeId::Integer(IntegerTypeVariant::I16),
224    {
225        CoreValue::TypedInteger(TypedInteger::I16(value)) => Ok(value),
226        CoreValue::TypedInteger(value) => value.to_i16().ok_or_else(|| ()),
227        CoreValue::TypedDecimal(value) => value.to_i16().ok_or_else(|| ()),
228    },
229    {
230        CoreValue::TypedInteger(TypedInteger::I16(value)) => Ok(value),
231    }
232);
233implement_rust_native_traits!(
234    i32,
235    CoreLibVariantTypeId::Integer(IntegerTypeVariant::I32),
236    {
237        CoreValue::TypedInteger(TypedInteger::I32(value)) => Ok(value),
238        CoreValue::TypedInteger(value) => value.to_i32().ok_or_else(|| ()),
239        CoreValue::TypedDecimal(value) => value.to_i32().ok_or_else(|| ()),
240    },
241    {
242        CoreValue::TypedInteger(TypedInteger::I32(value)) => Ok(value),
243    }
244);
245implement_rust_native_traits!(
246    i64,
247    CoreLibVariantTypeId::Integer(IntegerTypeVariant::I64),
248    {
249        CoreValue::TypedInteger(TypedInteger::I64(value)) => Ok(value),
250        CoreValue::TypedInteger(value) => value.to_i64().ok_or_else(|| ()),
251        CoreValue::TypedDecimal(value) => value.to_i64().ok_or_else(|| ()),
252    },
253    {
254        CoreValue::TypedInteger(TypedInteger::I64(value)) => Ok(value),
255    }
256);
257implement_rust_native_traits!(
258    i128,
259    CoreLibVariantTypeId::Integer(IntegerTypeVariant::I128),
260    {
261        CoreValue::TypedInteger(TypedInteger::I128(value)) => Ok(value),
262        CoreValue::TypedInteger(value) => value.to_i128().ok_or_else(|| ()),
263        CoreValue::TypedDecimal(value) => value.to_i128().ok_or_else(|| ()),
264    },
265    {
266        CoreValue::TypedInteger(TypedInteger::I128(value)) => Ok(value),
267    }
268);
269
270// isize depending on platform
271#[cfg(target_pointer_width = "32")]
272implement_rust_native_traits!(
273    isize,
274    CoreLibVariantTypeId::Integer(IntegerTypeVariant::I32),
275    {
276        CoreValue::TypedInteger(TypedInteger::I32(value)) => Ok(value as isize),
277        CoreValue::TypedInteger(value) => value.to_i32().map(|v| v as isize).ok_or_else(|| ()),
278        CoreValue::TypedDecimal(value) => value.to_i32().map(|v| v as isize).ok_or_else(|| ()),
279    },
280    {}
281);
282#[cfg(target_pointer_width = "64")]
283implement_rust_native_traits!(
284    isize,
285    CoreLibVariantTypeId::Integer(IntegerTypeVariant::I64),
286    {
287        CoreValue::TypedInteger(TypedInteger::I64(value)) => Ok(value as isize),
288        CoreValue::TypedInteger(value) => value.to_i64().map(|v| v as isize).ok_or_else(|| ()),
289        CoreValue::TypedDecimal(value) => value.to_i64().map(|v| v as isize).ok_or_else(|| ()),
290    },
291    {}
292);
293
294implement_rust_native_traits!(
295    f32,
296    CoreLibVariantTypeId::Decimal(DecimalTypeVariant::F32),
297    {
298        CoreValue::TypedDecimal(TypedDecimal::F32(value)) => Ok(value.into()),
299        CoreValue::TypedInteger(value) => value.to_f32().ok_or_else(|| ()),
300        CoreValue::TypedDecimal(value) => value.to_f32().ok_or_else(|| ()),
301    },
302    {
303        CoreValue::TypedDecimal(TypedDecimal::F32(value)) => Ok(value.as_ref()),
304    }
305);
306implement_rust_native_traits!(
307    f64,
308    CoreLibVariantTypeId::Decimal(DecimalTypeVariant::F64),
309    {
310        CoreValue::TypedDecimal(TypedDecimal::F64(value)) => Ok(value.into()),
311        CoreValue::TypedInteger(value) => value.to_f64().ok_or_else(|| ()),
312        CoreValue::TypedDecimal(value) => value.to_f64().ok_or_else(|| ()),
313    },
314    {
315        CoreValue::TypedDecimal(TypedDecimal::F64(value)) => Ok(value.as_ref()),
316    }
317);
318implement_rust_native_traits!(
319    String,
320    CoreLibBaseTypeId::Text,
321    {
322        CoreValue::Text(Text(value)) => Ok(value),
323    },
324    {
325        CoreValue::Text(Text(value)) => Ok(value),
326    }
327);
328impl DatexNativeOps for String {}
329impl DatexNativeOps for bool {}
330
331macro_rules! impl_native_add {
332    ($($ty:ty),*) => {
333        $(
334            impl DatexNativeOps for $ty {
335                fn add_native(
336                    &self,
337                    rhs: &dyn DatexNative,
338                ) -> Option<Box<dyn DatexNative>> {
339                    let rhs = rhs.as_any().downcast_ref::<$ty>()?;
340                    Some(Box::new(*self + *rhs))
341                }
342            }
343        )*
344    };
345}
346
347impl_native_add!(
348    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
349);
350
351// &str
352impl<'a> TryFrom<&'a CoreValue> for &'a str {
353    type Error = ();
354
355    fn try_from(value: &'a CoreValue) -> Result<Self, Self::Error> {
356        match value {
357            CoreValue::Text(Text::String(value)) => Ok(value.as_str()),
358            _ => Err(()),
359        }
360    }
361}
362
363impl<'a> TryFrom<&'a Value> for &'a str {
364    type Error = ();
365
366    fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
367        value.try_as::<String>().map(|s| s.as_str()).ok_or(())
368    }
369}
370impl<'a> TryFrom<&'a ValueContainer> for &'a str {
371    type Error = ();
372
373    fn try_from(value: &'a ValueContainer) -> Result<Self, Self::Error> {
374        match value {
375            ValueContainer::Local(value) => value.try_into(),
376            _ => Err(()),
377        }
378    }
379}
380impl GetDatexType for &str {
381    fn datex_type(_context: &mut SharedReferencesCache) -> Type {
382        Type::Definition(
383            TypeDefinition::CoreType(CoreLibBaseTypeId::Text.into()).into(),
384        )
385    }
386}
387
388impl GetDatexType for str {
389    fn datex_type(_context: &mut SharedReferencesCache) -> Type {
390        Type::Definition(
391            TypeDefinition::CoreType(CoreLibBaseTypeId::Text.into()).into(),
392        )
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399    use crate::{
400        traits::convert_value::ConvertValue,
401        values::{
402            core_value::CoreValue,
403            core_values::{boolean::Boolean, text::Text},
404            value::Value,
405        },
406    };
407
408    #[test]
409    fn try_without_context() {
410        // core rust types like String should be convertible to value without cache
411        let _ = Value::native("test".to_string());
412        let _ = "test".to_string().to_value();
413        let _ = Value::from("test".to_string());
414    }
415
416    #[test]
417    fn try_from_static_str_value() {
418        let value =
419            Value::from(CoreValue::Text(Text::StaticStr("Hello, World!")));
420        let result = value.try_as_str();
421        assert_eq!(result.unwrap(), "Hello, World!");
422    }
423
424    #[test]
425    fn to_value() {
426        let value = true;
427        let result: Value = Value::from(value);
428        assert_eq!(result, Value::from(CoreValue::Boolean(Boolean(true))));
429    }
430
431    #[test]
432    #[ignore = "FIXME - equality for native & native, native & core is not done yet see #839"]
433    fn try_boxed_to_value() {
434        let value = Box::new(true);
435        let result = Value::native_boxed(value);
436        assert_eq!(result, Value::from(CoreValue::Boolean(Boolean(true))));
437    }
438}