nuit_core/utils/
id.rs

1use std::fmt;
2
3use serde::{Serialize, Deserialize};
4
5// TODO: Investigate if we can use a `Cow<str>` to avoid unnecessary clones.
6// We'd likely have to fight with lifetimes a bit, since `Id` would likely
7// require a lifetime parameter now.
8
9/// An identifier for a view.
10#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(untagged)]
12pub enum Id {
13    Index(i64),
14    String(String),
15}
16
17impl Id {
18    pub fn index(value: impl Into<i64>) -> Self {
19        Self::Index(value.into())
20    }
21
22    pub fn string(value: impl Into<String>) -> Self {
23        Self::String(value.into())
24    }
25}
26
27impl Default for Id {
28    fn default() -> Self {
29        Self::Index(0)
30    }
31}
32
33impl fmt::Display for Id {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Self::Index(value) => write!(f, "{}", value),
37            Self::String(value) => write!(f, "{}", value),
38        }
39    }
40}
41
42macro_rules! impl_id_from_integer {
43    ($($tys:ty),*) => {
44        $(impl From<$tys> for Id {
45            fn from(value: $tys) -> Self {
46                Self::Index(value as i64)
47            }
48        })*
49    };
50}
51
52impl_id_from_integer!(
53    u8, u16, u32, u64, usize,
54    i8, i16, i32, i64, isize
55);
56
57impl From<String> for Id {
58    fn from(value: String) -> Self {
59        Self::String(value)
60    }
61}
62
63impl From<&str> for Id {
64    fn from(value: &str) -> Self {
65        Self::String(value.to_owned())
66    }
67}