schema_registry_api/domain/schema/
id.rs

1use std::fmt::Display;
2use std::str::FromStr;
3
4use crate::SchemaIdError;
5
6/// The schema id
7///
8/// You can build the schema id from a string or from an `u64`
9///
10/// ```rust
11/// # use schema_registry_api::SchemaId;
12/// let id = "1".parse::<SchemaId>().expect("Should be a valid id");
13/// let id2 = SchemaId::from(1);
14/// assert_eq!(id, id2);
15/// ```
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
17pub struct SchemaId(u64);
18
19impl FromStr for SchemaId {
20    type Err = SchemaIdError;
21
22    fn from_str(s: &str) -> Result<Self, Self::Err> {
23        let id = s.parse::<u64>().map_err(|_| SchemaIdError(s.to_string()))?;
24        Ok(Self(id))
25    }
26}
27
28impl From<u64> for SchemaId {
29    fn from(value: u64) -> Self {
30        SchemaId(value)
31    }
32}
33
34impl Display for SchemaId {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        write!(f, "{}", self.0)
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use assert2::{check, let_assert};
43
44    use super::*;
45
46    #[test]
47    fn should_build_from_str() {
48        let str = "42";
49        let result = SchemaId::from_str(str).unwrap();
50        check!(result == SchemaId(42));
51    }
52
53    #[test]
54    fn should_not_build_from_invalid_str() {
55        let str = "a42";
56        let result = SchemaId::from_str(str);
57        let_assert!(Err(_) = result);
58    }
59}