oca_bundle_semantics/state/oca/overlay/
link.rs

1use crate::state::{attribute::Attribute, oca::Overlay};
2use oca_ast_semantics::ast::OverlayType;
3use said::derivation::HashFunctionCode;
4use said::{sad::SerializationFormats, sad::SAD};
5use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer};
6use std::any::Any;
7use std::collections::HashMap;
8
9pub trait Links {
10    fn set_link(&mut self, t: String, link: String);
11}
12
13impl Links for Attribute {
14    fn set_link(&mut self, t: String, link: String) {
15        if let Some(links) = &mut self.links {
16            links.insert(t, link);
17        } else {
18            let mut links = HashMap::new();
19            links.insert(t, link);
20            self.links = Some(links);
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 LinkOverlay {
44    #[said]
45    #[serde(rename = "d")]
46    said: Option<said::SelfAddressingIdentifier>,
47    capture_base: Option<said::SelfAddressingIdentifier>,
48    #[serde(rename = "type")]
49    overlay_type: OverlayType,
50    pub target_bundle: String,
51    #[serde(serialize_with = "serialize_attributes")]
52    pub attribute_mapping: HashMap<String, String>,
53}
54
55impl Overlay for LinkOverlay {
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 attributes(&self) -> Vec<&String> {
72        self.attribute_mapping.keys().collect::<Vec<&String>>()
73    }
74
75    fn add(&mut self, attribute: &Attribute) {
76        if let Some(links) = &attribute.links {
77            if let Some(value) = links.get(&self.target_bundle) {
78                self.attribute_mapping
79                    .insert(attribute.name.clone(), value.to_string());
80            }
81        }
82    }
83}
84impl LinkOverlay {
85    pub fn new(t: String) -> Self {
86        let overlay_version = "1.1".to_string();
87        Self {
88            capture_base: None,
89            said: None,
90            overlay_type: OverlayType::Link(overlay_version),
91            target_bundle: t,
92            attribute_mapping: HashMap::new(),
93        }
94    }
95}