rof_rs/object_format/data_value/
struct_value.rs1use std::collections::HashMap;
2
3use crate::object_format::{
4 ignore_str_split::{ignoring_compliant_split_str, SplitIgnoreRule, SplitIgnoreRuleType},
5 property::{property_type::PropertyType, Property},
6 DataValue,
7};
8
9#[derive(Debug, Clone)]
12pub struct DataValueStruct {
13 properties: Vec<Property>,
14}
15
16impl DataValueStruct {
17 pub fn new(properties: Vec<Property>) -> Self {
18 Self { properties }
19 }
20}
21
22impl DataValue for DataValueStruct {
23 fn serialize(
24 &self,
25 pretty_print: bool,
26 tab_index: usize,
27 ) -> (
28 PropertyType, String, ) {
31 (
32 PropertyType::struct_type(),
33 match pretty_print {
34 true => format!(
35 "{{\n{}\n{}}}",
36 self.properties
37 .iter()
38 .map(|property| format!(
39 "{}{};",
40 "\t".repeat(tab_index + 1),
41 property.serialize(pretty_print, tab_index + 1)
42 ))
43 .collect::<Vec<String>>()
44 .join("\n"),
45 "\t".repeat(tab_index)
46 ),
47 false => format!(
48 "{{{}}}",
49 self.properties
50 .iter()
51 .map(|property| format!(
52 "{};",
53 property.serialize(pretty_print, tab_index + 1)
54 ))
55 .collect::<Vec<String>>()
56 .join("")
57 ),
58 },
59 )
60 }
61
62 fn deserialize(
63 serialized_type: &PropertyType,
64 serialized_value: &str,
65 ) -> Option<Box<dyn DataValue>>
66 where
67 Self: Sized,
68 {
69 if serialized_type.get_base_type() != "" && !serialized_type.is_struct() {
70 return None;
71 }
72
73 if !(serialized_value.starts_with("{")
74 && serialized_value.ends_with("}")
75 && serialized_value.chars().count() > 1)
76 {
77 return None;
78 }
79
80 let mut properties: Vec<Property> = Vec::new();
81
82 for serialized_property in ignoring_compliant_split_str(
83 &serialized_value[1..serialized_value.len() - 1].trim(),
84 ';',
85 true,
86 vec![
87 SplitIgnoreRule::new(SplitIgnoreRuleType::PAIR('"')).set_ecapsulates_raw_text(true),
88 SplitIgnoreRule::new(SplitIgnoreRuleType::PAIR('\''))
89 .set_ecapsulates_raw_text(true),
90 SplitIgnoreRule::new(SplitIgnoreRuleType::NEST('{', '}')),
91 ],
92 ) {
93 if serialized_property.trim().len() < 1 {
94 continue;
95 }
96
97 properties.push(Property::deserialize(serialized_property.trim()));
98 }
99
100 Some(Box::new(Self::new(properties)))
101 }
102
103 fn clone_data_value(&self) -> Box<dyn DataValue> {
104 Box::new(Self::new(self.properties.clone()))
105 }
106
107 fn as_struct_structure(&self) -> HashMap<String, Box<dyn DataValue>> {
108 let mut hashmap: HashMap<String, Box<dyn DataValue>> = HashMap::new();
109
110 for property in self.properties.iter() {
111 hashmap.insert(
112 property.property_index.clone(),
113 property.property_value.clone_data_value(),
114 );
115 }
116
117 hashmap
118 }
119}