Skip to main content

ante_protocol_shape/
id.rs

1// Copyright 2026 Antigma Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use serde::{Deserialize, Serialize};
5use ulid::Ulid;
6
7#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Copy)]
8pub struct Id {
9    prefix: [u8; Self::PREFIX_SIZE],
10    id: Ulid,
11}
12
13impl Id {
14    pub const PREFIX_SIZE: usize = 4;
15
16    pub fn new<S: AsRef<str>>(id: S) -> Self {
17        Self { prefix: Self::clamp_prefix(id), id: Ulid::generate() }
18    }
19
20    fn clamp_prefix<S: AsRef<str>>(id: S) -> [u8; Self::PREFIX_SIZE] {
21        let mut prefix = [0u8; Self::PREFIX_SIZE];
22        let bytes = id.as_ref().as_bytes();
23        let len = std::cmp::min(bytes.len(), Self::PREFIX_SIZE);
24        prefix[..len].copy_from_slice(&bytes[..len]);
25        prefix
26    }
27
28    pub fn op() -> Self {
29        Self::new("op")
30    }
31
32    pub fn evt() -> Self {
33        Self::new("evt")
34    }
35
36    pub fn ses() -> Self {
37        Self::new("ses")
38    }
39
40    pub fn step() -> Self {
41        Self::new("step")
42    }
43}
44
45impl std::fmt::Display for Id {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        for &b in self.prefix.iter().take_while(|&&b| b != 0) {
48            write!(f, "{}", b as char)?;
49        }
50        write!(f, "_{}", self.id)
51    }
52}
53
54impl std::fmt::Debug for Id {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        write!(f, "{self}")
57    }
58}
59
60impl Serialize for Id {
61    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
62    where
63        S: serde::Serializer,
64    {
65        serializer.serialize_str(&self.to_string())
66    }
67}
68
69impl<'de> Deserialize<'de> for Id {
70    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
71    where
72        D: serde::Deserializer<'de>,
73    {
74        let value = String::deserialize(deserializer)?;
75        value.parse().map_err(serde::de::Error::custom)
76    }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum ParseIdError {
81    MissingSeparator,
82    InvalidUlid,
83}
84
85impl std::fmt::Display for ParseIdError {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        match self {
88            Self::MissingSeparator => write!(f, "missing separator"),
89            Self::InvalidUlid => write!(f, "invalid ULID"),
90        }
91    }
92}
93
94impl std::error::Error for ParseIdError {}
95
96impl std::str::FromStr for Id {
97    type Err = ParseIdError;
98
99    fn from_str(s: &str) -> Result<Self, Self::Err> {
100        let (prefix_str, ulid_str) = s.split_once('_').ok_or(ParseIdError::MissingSeparator)?;
101        let id = Ulid::from_string(ulid_str).map_err(|_| ParseIdError::InvalidUlid)?;
102        Ok(Self { prefix: Self::clamp_prefix(prefix_str), id })
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn test_id_serde_roundtrip() {
112        let id = Id::new("evt");
113        let serialized = serde_json::to_string(&id).expect("serialize id");
114        assert_eq!(serialized, format!("\"{id}\""));
115
116        let deserialized: Id = serde_json::from_str(&serialized).expect("deserialize id");
117        assert_eq!(deserialized, id);
118    }
119}