oca_bundle/state/oca/overlay/
information.rs1use crate::state::{attribute::Attribute, oca::Overlay};
2use isolang::Language;
3use oca_ast::ast::OverlayType;
4use said::{sad::SerializationFormats, sad::SAD};
5use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer};
6use std::any::Any;
7use std::collections::HashMap;
8
9pub trait Information {
10 fn set_information(&mut self, l: Language, information: String);
11}
12
13impl Information for Attribute {
14 fn set_information(&mut self, l: Language, information: String) {
15 if let Some(informations) = &mut self.informations {
16 informations.insert(l, information);
17 } else {
18 let mut informations = HashMap::new();
19 informations.insert(l, information);
20 self.informations = Some(informations);
21 }
22 }
23}
24
25pub fn serialize_attributes<S>(
26 attributes: &HashMap<String, String>,
27 s: S,
28) -> Result<S::Ok, S::Error>
29where
30 S: Serializer,
31{
32 use std::collections::BTreeMap;
33
34 let mut ser = s.serialize_map(Some(attributes.len()))?;
35 let sorted_attributes: BTreeMap<_, _> = attributes.iter().collect();
36 for (k, v) in sorted_attributes {
37 ser.serialize_entry(k, v)?;
38 }
39 ser.end()
40}
41
42#[derive(SAD, Serialize, Deserialize, Debug, Clone)]
43pub struct InformationOverlay {
44 #[said]
45 #[serde(rename = "d")]
46 said: Option<said::SelfAddressingIdentifier>,
47 language: Language,
48 #[serde(rename = "type")]
49 overlay_type: OverlayType,
50 capture_base: Option<said::SelfAddressingIdentifier>,
51 #[serde(serialize_with = "serialize_attributes")]
52 pub attribute_information: HashMap<String, String>,
53}
54
55impl Overlay for InformationOverlay {
56 fn as_any(&self) -> &dyn Any {
57 self
58 }
59 fn capture_base(&self) -> &Option<said::SelfAddressingIdentifier> {
60 &self.capture_base
61 }
62 fn set_capture_base(&mut self, said: &said::SelfAddressingIdentifier) {
63 self.capture_base = Some(said.clone());
64 }
65 fn overlay_type(&self) -> &OverlayType {
66 &self.overlay_type
67 }
68 fn said(&self) -> &Option<said::SelfAddressingIdentifier> {
69 &self.said
70 }
71 fn language(&self) -> Option<&Language> {
72 Some(&self.language)
73 }
74 fn attributes(&self) -> Vec<&String> {
75 self.attribute_information.keys().collect::<Vec<&String>>()
76 }
77
78 fn add(&mut self, attribute: &Attribute) {
79 if let Some(informations) = &attribute.informations {
80 if let Some(value) = informations.get(&self.language) {
81 self.attribute_information
82 .insert(attribute.name.clone(), value.to_string());
83 }
84 }
85 }
86}
87impl InformationOverlay {
88 pub fn new(lang: Language) -> InformationOverlay {
89 InformationOverlay {
90 capture_base: None,
91 said: None,
92 overlay_type: OverlayType::Information,
93 language: lang,
94 attribute_information: HashMap::new(),
95 }
96 }
97}