mech_core/structures/
map.rs1use crate::*;
2use indexmap::map::*;
3
4#[cfg(feature = "map")]
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub struct MechMap {
9 pub key_kind: ValueKind,
10 pub value_kind: ValueKind,
11 pub num_elements: usize,
12 pub map: IndexMap<Value,Value>,
13}
14
15#[cfg(feature = "map")]
16impl MechMap {
17
18 #[cfg(feature = "pretty_print")]
19 pub fn to_html(&self) -> String {
20 let mut src = String::new();
21 for (i, (key, value)) in self.map.iter().enumerate() {
22 let k = key.to_html();
23 let v = value.to_html();
24 if i == 0 {
25 src = format!("{}: {}", k, v);
26 } else {
27 src = format!("{}, {}: {}", src, k, v);
28 }
29 }
30 format!("<span class=\"mech-map\"><span class=\"mech-start-brace\">{{</span>{}<span class=\"mech-end-brace\">}}</span></span>",src)
31 }
32
33 pub fn kind(&self) -> ValueKind {
34 ValueKind::Map(Box::new(self.key_kind.clone()), Box::new(self.value_kind.clone()))
35 }
36
37 pub fn size_of(&self) -> usize {
38 self.map.iter().map(|(k,v)| k.size_of() + v.size_of()).sum()
39 }
40
41 pub fn from_vec(vec: Vec<(Value,Value)>) -> MechMap {
42 let mut map = IndexMap::new();
43 for (k,v) in vec {
44 map.insert(k,v);
45 }
46 MechMap{
47 key_kind: map.keys().next().unwrap().kind(),
48 value_kind: map.values().next().unwrap().kind(),
49 num_elements: map.len(),
50 map}
51 }
52}
53
54#[cfg(feature = "pretty_print")]
55impl PrettyPrint for MechMap {
56 fn pretty_print(&self) -> String {
57 let mut lines = Vec::new();
58
59 for (k, v) in &self.map {
60 lines.push(format!(
61 " {}: {}",
62 k.pretty_print(),
63 v.pretty_print()
64 ));
65 }
66
67 format!("{{\n{}\n}}", lines.join("\n"))
68 }
69}
70
71#[cfg(feature = "map")]
72impl Hash for MechMap {
73 fn hash<H: Hasher>(&self, state: &mut H) {
74 for x in self.map.iter() {
75 x.hash(state)
76 }
77 }
78}
79
80#[derive(Debug, Clone)]
81pub struct MapKeyKindMismatchError {
82 pub expected_kind: ValueKind,
83 pub actual_kind: ValueKind,
84}
85impl MechErrorKind2 for MapKeyKindMismatchError {
86 fn name(&self) -> &str {
87 "MapKeyKindMismatch"
88 }
89
90 fn message(&self) -> String {
91 format!(
92 "Map key kind mismatch (expected `{}`, found `{}`).",
93 self.expected_kind, self.actual_kind
94 )
95 }
96}
97
98#[derive(Debug, Clone)]
99pub struct MapValueKindMismatchError {
100 pub expected_kind: ValueKind,
101 pub actual_kind: ValueKind,
102}
103impl MechErrorKind2 for MapValueKindMismatchError {
104 fn name(&self) -> &str {
105 "MapValueKindMismatch"
106 }
107
108 fn message(&self) -> String {
109 format!(
110 "Map value kind mismatch (expected `{}`, found `{}`).",
111 self.expected_kind, self.actual_kind
112 )
113 }
114}