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