Skip to main content

datex_core/traits/
convert_value.rs

1use crate::{
2    prelude::*,
3    traits::convert_parts::{FromParts, HasPartsKind, IntoParts, PartsKind},
4    values::value::Value,
5};
6
7pub trait ConvertValue {
8    fn to_value(self) -> Value;
9
10    fn try_from_value(value: Value) -> Result<Self, Value>
11    where
12        Self: Sized;
13
14    fn try_borrow_from_value(value: &Value) -> Result<&Self, ()>;
15
16    fn try_borrow_mut_from_value(value: &mut Value) -> Result<&mut Self, ()>;
17
18    /// Tries to convert a [Value] into the specified type [T].
19    /// First, it attempts a direct conversion (downcast) of the [Value] into the type [T].
20    /// If that fails, it tries to convert the [Value] into map or list parts and then into the type [T].
21    fn try_convert_from_value(value: Value) -> Result<Self, ()>
22    where
23        Self: FromParts + Sized,
24    {
25        // first try to convert (downcast) the value container directly into the type T
26        let val = Self::try_from_value(value);
27        match val {
28            Ok(value) => Ok(value),
29            // otherwise, try to convert the value container into map or list parts and then into the type T
30            Err(value) => {
31                let classification = value.unresolved_classification();
32                let tag = classification.tag_str();
33
34                match value.parts_kind() {
35                    PartsKind::Map => {
36                        let map_parts = Box::new(value).try_into_map_parts();
37                        if let Ok(map) = map_parts {
38                            Self::try_from_map_parts_with_tag(map, tag)
39                        } else {
40                            Err(())
41                        }
42                    }
43                    PartsKind::List => {
44                        let list_parts = Box::new(value).try_into_list_parts();
45                        if let Ok(list) = list_parts {
46                            Self::try_from_list_parts_with_tag(list, tag)
47                        } else {
48                            Err(())
49                        }
50                    }
51                    PartsKind::SingleValue => {
52                        let single_value_parts =
53                            Box::new(value).try_into_single_value();
54                        if let Ok(single_value) = single_value_parts {
55                            Self::try_from_single_value_with_tag(
56                                single_value,
57                                tag,
58                            )
59                        } else {
60                            Err(())
61                        }
62                    }
63                    PartsKind::None => Err(()),
64                }
65            }
66        }
67    }
68}