Skip to main content

systemprompt_identifiers/macros/
token.rs

1#[macro_export]
2macro_rules! define_token {
3    ($name:ident) => {
4        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
5        #[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
6        #[cfg_attr(feature = "sqlx", sqlx(transparent))]
7        #[serde(transparent)]
8        pub struct $name(String);
9
10        impl $name {
11            pub fn new(token: impl Into<String>) -> Self {
12                Self(token.into())
13            }
14
15            pub fn as_str(&self) -> &str {
16                &self.0
17            }
18
19            #[must_use]
20            pub fn redacted(&self) -> String {
21                let len = self.0.len();
22                if len <= 16 {
23                    "*".repeat(len.min(8))
24                } else {
25                    format!("{}...{}", &self.0[..8], &self.0[len - 4..])
26                }
27            }
28        }
29
30        impl std::fmt::Display for $name {
31            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32                write!(f, "{}", self.redacted())
33            }
34        }
35
36        impl From<String> for $name {
37            fn from(s: String) -> Self {
38                Self(s)
39            }
40        }
41
42        impl From<&str> for $name {
43            fn from(s: &str) -> Self {
44                Self(s.to_string())
45            }
46        }
47
48        impl AsRef<str> for $name {
49            fn as_ref(&self) -> &str {
50                &self.0
51            }
52        }
53
54        impl $crate::ToDbValue for $name {
55            fn to_db_value(&self) -> $crate::DbValue {
56                $crate::DbValue::String(self.0.clone())
57            }
58        }
59
60        impl $crate::ToDbValue for &$name {
61            fn to_db_value(&self) -> $crate::DbValue {
62                $crate::DbValue::String(self.0.clone())
63            }
64        }
65    };
66}