Skip to main content

cesr/core/matter/code/
verser.rs

1use super::cesr_code::CesrCode;
2use super::matter_code::MatterCode;
3use super::sealed::Sealed;
4use crate::core::matter::error::ValidationError;
5#[cfg(feature = "alloc")]
6#[allow(
7    unused_imports,
8    reason = "alloc prelude items; subset used per cfg/feature combination"
9)]
10use alloc::string::ToString;
11
12/// CESR codes for version/protocol encoding primitives.
13#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
14pub enum VerserCode {
15    /// Tag7: 7 B64 chars for protocol-only version.
16    Tag7,
17    /// Tag10: 10 B64 chars for protocol + genus version.
18    Tag10,
19}
20
21impl Sealed for VerserCode {}
22
23impl CesrCode for VerserCode {
24    fn to_matter_code(&self) -> MatterCode {
25        match self {
26            Self::Tag7 => MatterCode::Tag7,
27            Self::Tag10 => MatterCode::Tag10,
28        }
29    }
30
31    fn as_str(&self) -> &'static str {
32        match self {
33            Self::Tag7 => "Y",
34            Self::Tag10 => "0O",
35        }
36    }
37}
38
39impl TryFrom<MatterCode> for VerserCode {
40    type Error = ValidationError;
41
42    fn try_from(code: MatterCode) -> Result<Self, Self::Error> {
43        match code {
44            MatterCode::Tag7 => Ok(Self::Tag7),
45            MatterCode::Tag10 => Ok(Self::Tag10),
46            _ => Err(ValidationError::UnknownMatterCode(code.to_string())),
47        }
48    }
49}
50
51impl From<VerserCode> for MatterCode {
52    fn from(code: VerserCode) -> Self {
53        code.to_matter_code()
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60    use crate::core::matter::code::MatterCode;
61
62    #[test]
63    fn verser_code_to_matter_code_roundtrip() {
64        let codes = [
65            (VerserCode::Tag7, MatterCode::Tag7),
66            (VerserCode::Tag10, MatterCode::Tag10),
67        ];
68        for (vc, mc) in codes {
69            assert_eq!(vc.to_matter_code(), mc);
70            assert_eq!(VerserCode::try_from(mc).unwrap(), vc);
71            assert_eq!(MatterCode::from(vc), mc);
72        }
73    }
74
75    #[test]
76    fn verser_code_rejects_non_verser() {
77        assert!(VerserCode::try_from(MatterCode::Ed25519).is_err());
78        assert!(VerserCode::try_from(MatterCode::Blake3_256).is_err());
79        assert!(VerserCode::try_from(MatterCode::Short).is_err());
80    }
81
82    #[test]
83    fn verser_code_as_str() {
84        assert_eq!(VerserCode::Tag7.as_str(), "Y");
85        assert_eq!(VerserCode::Tag10.as_str(), "0O");
86    }
87}