Skip to main content

deed/
id.rs

1use serde::{Deserialize, Serialize};
2
3use crate::error::{Error, Result};
4use crate::kind::Kind;
5
6/// Accession: `deed-<kind>-<slug>`.
7#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
8pub struct DeedId(String);
9
10impl DeedId {
11    pub fn parse(raw: &str) -> Result<Self> {
12        let rest = raw
13            .strip_prefix("deed-")
14            .ok_or_else(|| Error::InvalidId(raw.into()))?;
15        let (kind, slug) = rest
16            .split_once('-')
17            .ok_or_else(|| Error::InvalidId(raw.into()))?;
18        Kind::parse(kind)?;
19        if slug.is_empty()
20            || !slug
21                .bytes()
22                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
23        {
24            return Err(Error::InvalidId(raw.into()));
25        }
26        Ok(Self(raw.to_string()))
27    }
28
29    pub fn mint(kind: &Kind, slug: &str) -> Result<Self> {
30        Self::parse(&format!("deed-{}-{slug}", kind.token()))
31    }
32
33    pub fn as_str(&self) -> &str {
34        &self.0
35    }
36}
37
38impl std::fmt::Display for DeedId {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.write_str(&self.0)
41    }
42}