starbase_id/
lib.rs

1use compact_str::CompactString;
2use serde::{Deserialize, Serialize};
3use std::borrow::{Borrow, Cow};
4use std::fmt;
5use std::ops::Deref;
6
7/// A generic identifier.
8#[derive(Clone, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
9pub struct Id(CompactString);
10
11impl Id {
12    pub fn raw<S: AsRef<str>>(id: S) -> Id {
13        Id(CompactString::new(id))
14    }
15
16    pub fn as_str(&self) -> &str {
17        &self.0
18    }
19
20    pub fn as_compact_str(&self) -> &CompactString {
21        &self.0
22    }
23}
24
25impl fmt::Debug for Id {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        write!(f, "{}", self.0)
28    }
29}
30
31impl fmt::Display for Id {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        write!(f, "{}", self.0)
34    }
35}
36
37impl Deref for Id {
38    type Target = str;
39
40    fn deref(&self) -> &Self::Target {
41        &self.0
42    }
43}
44
45impl AsRef<str> for Id {
46    fn as_ref(&self) -> &str {
47        &self.0
48    }
49}
50
51impl AsRef<Id> for Id {
52    fn as_ref(&self) -> &Id {
53        self
54    }
55}
56
57impl Borrow<str> for Id {
58    fn borrow(&self) -> &str {
59        &self.0
60    }
61}
62
63macro_rules! gen_partial_eq {
64    ($ty:ty) => {
65        impl PartialEq<$ty> for Id {
66            fn eq(&self, other: &$ty) -> bool {
67                self.0 == other
68            }
69        }
70    };
71}
72
73gen_partial_eq!(str);
74gen_partial_eq!(&str);
75gen_partial_eq!(String);
76gen_partial_eq!(&String);
77gen_partial_eq!(Cow<'_, str>);
78gen_partial_eq!(&Cow<'_, str>);
79gen_partial_eq!(Box<str>);
80gen_partial_eq!(&Box<str>);
81
82macro_rules! gen_from {
83    ($ty:ty) => {
84        impl From<$ty> for Id {
85            fn from(value: $ty) -> Self {
86                Self::raw(value)
87            }
88        }
89    };
90}
91
92gen_from!(&str);
93gen_from!(String);
94gen_from!(&String);
95gen_from!(Cow<'_, str>);
96gen_from!(&Cow<'_, str>);
97gen_from!(Box<str>);
98gen_from!(&Box<str>);
99
100#[cfg(feature = "schematic")]
101impl schematic::Schematic for Id {
102    fn schema_name() -> Option<String> {
103        Some("Id".into())
104    }
105
106    fn build_schema(mut schema: schematic::SchemaBuilder) -> schematic::Schema {
107        schema.string_default()
108    }
109}