cedar_policy_core/est/
annotation.rs

1/*
2 * Copyright Cedar Contributors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::collections::BTreeMap;
18
19use serde::{Deserialize, Serialize};
20
21use crate::ast::{self, Annotation, AnyId};
22#[cfg(feature = "wasm")]
23extern crate tsify;
24
25/// Similar to [`ast::Annotations`] but allow annotation value to be `null`
26#[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    /// Create a new empty `Annotations` (with no annotations)
39    pub fn new() -> Self {
40        Self(BTreeMap::new())
41    }
42    /// Tell if it's empty
43    pub fn is_empty(&self) -> bool {
44        self.0.is_empty()
45    }
46}
47
48impl From<Annotations> for ast::Annotations {
49    fn from(value: Annotations) -> Self {
50        ast::Annotations::from_iter(
51            value
52                .0
53                .into_iter()
54                .map(|(key, value)| (key, value.unwrap_or_default())),
55        )
56    }
57}
58
59impl From<ast::Annotations> for Annotations {
60    fn from(value: ast::Annotations) -> Self {
61        Self(
62            value
63                .into_iter()
64                .map(|(key, value)| (key, Some(value)))
65                .collect(),
66        )
67    }
68}
69
70impl std::fmt::Display for Annotations {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        for (k, v) in &self.0 {
73            if let Some(anno) = v {
74                writeln!(f, "@{k}({anno})")?
75            } else {
76                writeln!(f, "@{k}")?
77            }
78        }
79        Ok(())
80    }
81}
82
83impl Default for Annotations {
84    fn default() -> Self {
85        Self::new()
86    }
87}