Skip to main content

keel_policy/
ids.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3use uuid::Uuid;
4
5macro_rules! id_newtype {
6    ($name:ident, $prefix:literal) => {
7        #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
8        #[serde(transparent)]
9        pub struct $name(String);
10
11        impl $name {
12            pub fn new() -> Self {
13                Self(format!("{}-{}", $prefix, Uuid::new_v4().simple()))
14            }
15
16            pub fn from_string(s: impl Into<String>) -> Self {
17                Self(s.into())
18            }
19
20            pub fn as_str(&self) -> &str {
21                &self.0
22            }
23        }
24
25        impl Default for $name {
26            fn default() -> Self {
27                Self::new()
28            }
29        }
30
31        impl fmt::Display for $name {
32            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33                f.write_str(&self.0)
34            }
35        }
36
37        impl From<String> for $name {
38            fn from(s: String) -> Self {
39                Self(s)
40            }
41        }
42
43        impl AsRef<str> for $name {
44            fn as_ref(&self) -> &str {
45                &self.0
46            }
47        }
48    };
49}
50
51id_newtype!(PolicyId, "pol");
52id_newtype!(SpaceId, "spc");
53id_newtype!(TaskId, "tsk");