cedar_policy_core/est/
annotation.rs1use std::collections::BTreeMap;
18
19use serde::{Deserialize, Serialize};
20
21use crate::ast::{self, Annotation, AnyId};
22#[cfg(feature = "wasm")]
23extern crate tsify;
24
25#[derive(Serialize, Deserialize, Clone, Hash, Eq, PartialEq, PartialOrd, Ord, Debug)]
27#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
28#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
29pub struct Annotations(
30 #[serde(default)]
31 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
32 #[serde(with = "::serde_with::rust::maps_duplicate_key_is_error")]
33 #[cfg_attr(feature = "wasm", tsify(type = "Record<string, Annotation>"))]
34 pub BTreeMap<AnyId, Option<Annotation>>,
35);
36
37impl Annotations {
38 pub fn new() -> Self {
40 Self(BTreeMap::new())
41 }
42 pub fn is_empty(&self) -> bool {
44 self.0.is_empty()
45 }
46 pub fn fmt_indented(
48 &self,
49 f: &mut std::fmt::Formatter<'_>,
50 base_indentation: usize,
51 ) -> std::fmt::Result {
52 let base_indent = " ".repeat(base_indentation);
53 for (k, v) in &self.0 {
54 if let Some(anno) = v {
55 writeln!(f, "{base_indent}@{k}({anno})")?
56 } else {
57 writeln!(f, "{base_indent}@{k}")?
58 }
59 }
60 Ok(())
61 }
62}
63
64impl From<Annotations> for ast::Annotations {
65 fn from(value: Annotations) -> Self {
66 ast::Annotations::from_iter(
67 value
68 .0
69 .into_iter()
70 .map(|(key, value)| (key, value.unwrap_or_default())),
71 )
72 }
73}
74
75impl From<ast::Annotations> for Annotations {
76 fn from(value: ast::Annotations) -> Self {
77 Self(
78 value
79 .into_iter()
80 .map(|(key, value)| (key, Some(value)))
81 .collect(),
82 )
83 }
84}
85
86impl std::fmt::Display for Annotations {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 self.fmt_indented(f, 0)
89 }
90}
91
92impl Default for Annotations {
93 fn default() -> Self {
94 Self::new()
95 }
96}