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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use crate::error::Error;
use serde::{Deserialize, Serialize};
use std::{fmt, str::FromStr};

#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ShortId([u8; 8]);

impl ShortId {
    pub fn new() -> Self {
        Default::default()
    }
}

impl From<[u8; 7]> for ShortId {
    fn from(id: [u8; 7]) -> Self {
        let mut bytes = [0; 8];
        bytes[1..].copy_from_slice(&id);
        Self(bytes)
    }
}

impl fmt::Debug for ShortId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ShortId({})", self)
    }
}

impl fmt::Display for ShortId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0[0] == 0 {
            write!(f, "{}", hex::encode(&self.0[1..]))
        } else {
            let len = self.0.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1);
            write!(f, "{}", String::from_utf8_lossy(&self.0[..len]))
        }
    }
}

impl FromStr for ShortId {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut id = [0; 8];
        if hex::decode_to_slice(s, &mut id[1..]).is_ok() {
            return Ok(ShortId(id));
        }
        let str = s.to_ascii_lowercase();
        if !str.is_ascii() || str.len() > 8 {
            return Err(Error::InvalidShortId { id: s.to_string() });
        }
        let bytes = str.as_bytes();
        let len = bytes.len().min(id.len());
        id[..len].copy_from_slice(&bytes[..len]);
        Ok(ShortId(id))
    }
}

impl Serialize for ShortId {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for ShortId {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        ShortId::from_str(&s).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn parse_hex() {
        let id = ShortId::from_str("f9cf7e3faa1aca").unwrap();
        assert_eq!(id.to_string(), "f9cf7e3faa1aca");
    }

    #[test]
    fn parse_hypen_id() {
        let id = ShortId::from_str("djs-vjd").unwrap();
        assert_eq!(id.to_string(), "djs-vjd");
    }
}