aboutsummaryrefslogtreecommitdiff
path: root/src/ids.rs
blob: 05dac7e3d80496b427da3f5875f2e7feff24b324 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use std::fmt::Display;
use std::fmt::Error;

pub trait Identifier: Display {
    fn value(&self) -> &str;
}
/// Meant to be a helpful trait allowing anything that can be
/// identified by the type specified in `ById`.
pub trait AsIdentifier<ById: Identifier> {
    fn as_id(&self) -> &ById;
}

impl<T> AsIdentifier<T> for T
where
    T: Identifier,
{
    fn as_id(&self) -> &T {
        &self
    }
}

impl<T> AsIdentifier<T> for &T
where
    T: Identifier,
{
    fn as_id(&self) -> &T {
        self
    }
}

macro_rules! identifer {
    ($name:ident) => {
        #[derive(serde::Serialize, serde::Deserialize, Debug, Eq, PartialEq, Hash, Clone)]
        #[serde(transparent)]
        pub struct $name(String);

        impl Identifier for $name {
            fn value(&self) -> &str {
                &self.0
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(
                &self,
                f: &mut std::fmt::Formatter<'_>,
            ) -> std::fmt::Result {
                self.0.fmt(f)
            }
        }

        impl std::str::FromStr for $name {
            type Err = Error;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                Ok($name(s.to_string()))
            }
        }
    };
}

identifer!(DatabaseId);
identifer!(PageId);
identifer!(BlockId);
identifer!(UserId);
identifer!(PropertyId);

impl From<PageId> for BlockId {
    fn from(page_id: PageId) -> Self {
        BlockId(page_id.0)
    }
}