oca_bundle/state/oca/
capture_base.rs1use crate::state::attribute::Attribute;
2use indexmap::IndexMap;
3use oca_ast::ast::NestedAttrType;
4use said::{sad::SerializationFormats, sad::SAD};
5use serde::{ser::SerializeMap, ser::SerializeSeq, Deserialize, Serialize, Serializer};
6
7pub fn serialize_attributes<S>(
8 attributes: &IndexMap<String, NestedAttrType>,
9 s: S,
10) -> Result<S::Ok, S::Error>
11where
12 S: Serializer,
13{
14 use std::collections::BTreeMap;
15
16 let mut ser = s.serialize_map(Some(attributes.len()))?;
17 let sorted_attributes: BTreeMap<_, _> = attributes.iter().collect();
18 for (k, v) in sorted_attributes {
19 ser.serialize_entry(k, v)?;
20 }
21 ser.end()
22}
23
24pub fn serialize_flagged_attributes<S>(attributes: &[String], s: S) -> Result<S::Ok, S::Error>
25where
26 S: Serializer,
27{
28 let mut ser = s.serialize_seq(Some(attributes.len()))?;
29
30 let mut sorted_flagged_attributes = attributes.to_owned();
31 sorted_flagged_attributes.sort();
32 for attr in sorted_flagged_attributes {
33 ser.serialize_element(&attr)?;
34 }
35 ser.end()
36}
37
38#[derive(SAD, Serialize, Deserialize, Debug, Clone)]
39pub struct CaptureBase {
40 #[said]
41 #[serde(rename = "d")]
42 pub said: Option<said::SelfAddressingIdentifier>,
43 #[serde(rename = "type")]
44 pub schema_type: String,
45 pub classification: String,
46 #[serde(serialize_with = "serialize_attributes")]
47 pub attributes: IndexMap<String, NestedAttrType>,
48 #[serde(serialize_with = "serialize_flagged_attributes")]
49 pub flagged_attributes: Vec<String>,
50}
51
52impl Default for CaptureBase {
53 fn default() -> Self {
54 Self::new()
55 }
56}
57
58impl CaptureBase {
59 pub fn new() -> CaptureBase {
60 CaptureBase {
61 schema_type: String::from("spec/capture_base/1.0"),
62 said: None,
63 classification: String::from(""),
64 attributes: IndexMap::new(),
65 flagged_attributes: Vec::new(),
66 }
67 }
68
69 pub fn set_classification(&mut self, classification: &str) {
70 self.classification = classification.to_string();
71 }
72
73 pub fn add(&mut self, attribute: &Attribute) {
74 self.attributes.insert(
88 attribute.name.clone(),
89 attribute.attribute_type.clone().unwrap(),
90 );
91 if attribute.is_flagged {
92 self.flagged_attributes.push(attribute.name.clone());
93 }
94 }
95
96 pub fn fill_said(&mut self) {
97 self.compute_digest(); }
99
100 pub fn sign(&mut self) {
101 self.fill_said();
102 }
103}