oca_bundle/state/oca/overlay/
entry.rs1use crate::state::{attribute::Attribute, entries::EntriesElement, 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 Entries {
10 fn set_entry(&mut self, l: Language, entry: EntriesElement);
11}
12
13impl Entries for Attribute {
14 fn set_entry(&mut self, l: Language, entry: EntriesElement) {
15 if let Some(entries) = &mut self.entries {
16 entries.insert(l, entry);
17 } else {
18 let mut entries = HashMap::new();
19 entries.insert(l, entry);
20 self.entries = Some(entries);
21 }
22 }
23}
24
25pub fn serialize_attributes<S>(
26 attributes: &HashMap<String, EntriesElement>,
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 EntryOverlay {
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_entries: HashMap<String, EntriesElement>,
53}
54
55impl Overlay for EntryOverlay {
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 said(&self) -> &Option<said::SelfAddressingIdentifier> {
66 &self.said
67 }
68 fn overlay_type(&self) -> &OverlayType {
69 &self.overlay_type
70 }
71 fn language(&self) -> Option<&Language> {
72 Some(&self.language)
73 }
74 fn attributes(&self) -> Vec<&String> {
75 self.attribute_entries.keys().collect::<Vec<&String>>()
76 }
77
78 fn add(&mut self, attribute: &Attribute) {
79 if let Some(entries) = &attribute.entries {
80 if let Some(tr) = entries.get(&self.language) {
81 self.attribute_entries
82 .insert(attribute.name.clone(), tr.clone());
83 }
84 }
85 }
86}
87impl EntryOverlay {
88 pub fn new(lang: Language) -> EntryOverlay {
89 EntryOverlay {
90 capture_base: None,
91 said: None,
92 overlay_type: OverlayType::Entry,
93 language: lang,
94 attribute_entries: HashMap::new(),
95 }
96 }
97}