Skip to main content

base/
id.rs

1//! BASE58(UUID v4) 字符串身份。
2//!
3//! 与 Atta 顶层 `Cloud/src/store/id.rs::Id` 兼容;合并。
4
5use serde::{Deserialize, Serialize};
6use std::fmt;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
9#[serde(transparent)]
10pub struct Id(#[serde(with = "id_serde")] [u8; 16]);
11
12#[derive(thiserror::Error, Debug)]
13#[non_exhaustive]
14pub enum IdError {
15    #[error("base58 decode: {0}")]
16    Base58(#[from] bs58::decode::Error),
17    #[error("expected 16 bytes, got {0}")]
18    Length(usize),
19}
20
21impl Id {
22    /// 随机生成一个 v4 UUID 包成 Id。生成入口仅此一处。
23    pub fn new() -> Self {
24        Self(*uuid::Uuid::new_v4().as_bytes())
25    }
26
27    /// The same sixteen bytes an id is made of, from somewhere other than the
28    /// system's randomness — see
29    /// [`Environment`](crate::interface::environment::Environment).
30    pub fn from_bytes(bytes: [u8; 16]) -> Self {
31        Self(bytes)
32    }
33
34    /// 从外部字符串解码并验证 16 字节。
35    pub fn parse(s: &str) -> Result<Self, IdError> {
36        let v = bs58::decode(s).into_vec()?;
37        if v.len() != 16 {
38            return Err(IdError::Length(v.len()));
39        }
40        let mut buf = [0u8; 16];
41        buf.copy_from_slice(&v);
42        Ok(Self(buf))
43    }
44
45    /// Raw 16-byte UUID payload (read-only view).
46    pub fn as_bytes(&self) -> &[u8; 16] {
47        &self.0
48    }
49}
50
51impl Default for Id {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl fmt::Display for Id {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.write_str(&bs58::encode(self.0).into_string())
60    }
61}
62
63mod id_serde {
64    use serde::{Deserialize, Deserializer, Serializer};
65    /// serde adapter — encodes the 16-byte UUID as BASE58 text.
66    pub fn serialize<S: Serializer>(bytes: &[u8; 16], s: S) -> Result<S::Ok, S::Error> {
67        s.serialize_str(&bs58::encode(bytes).into_string())
68    }
69    /// serde adapter — decodes BASE58 text back to 16 bytes.
70    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 16], D::Error> {
71        let s = String::deserialize(d)?;
72        let v = bs58::decode(&s)
73            .into_vec()
74            .map_err(serde::de::Error::custom)?;
75        if v.len() != 16 {
76            return Err(serde::de::Error::custom(format!(
77                "expected 16 bytes, got {}",
78                v.len()
79            )));
80        }
81        let mut buf = [0u8; 16];
82        buf.copy_from_slice(&v);
83        Ok(buf)
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[test]
92    fn roundtrip() {
93        let a = Id::new();
94        let s = a.to_string();
95        let b = Id::parse(&s).unwrap();
96        assert_eq!(a, b);
97        // 16 字节的 BASE58 编码常见 22 字符;首字节为 0 时会输出 21(base58 不带 padding)
98        assert!(
99            (21..=22).contains(&s.len()),
100            "unexpected length: {}",
101            s.len()
102        );
103    }
104
105    #[test]
106    fn rejects_bad_length() {
107        let bad = bs58::encode([0u8; 8]).into_string();
108        assert!(Id::parse(&bad).is_err());
109    }
110
111    #[test]
112    fn json_roundtrip() {
113        let a = Id::new();
114        let s = serde_json::to_string(&a).unwrap();
115        let b: Id = serde_json::from_str(&s).unwrap();
116        assert_eq!(a, b);
117    }
118}