Skip to main content

r402_core/wire/
version.rs

1//! Const-parameterized protocol version marker.
2
3use std::fmt::{self, Display, Formatter};
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6
7/// A compile-time protocol-version marker that serializes as a bare integer.
8///
9/// The const parameter `N` encodes the version. Deserialization rejects
10/// values other than `N`, giving compile-time and runtime certainty that
11/// a message carries the expected protocol version.
12#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, Hash)]
13pub struct Version<const N: u8>;
14
15impl<const N: u8> Version<N> {
16    /// The numeric value of this version marker.
17    pub const VALUE: u8 = N;
18}
19
20impl<const N: u8> PartialEq<u8> for Version<N> {
21    fn eq(&self, other: &u8) -> bool {
22        *other == N
23    }
24}
25
26impl<const N: u8> From<Version<N>> for u8 {
27    fn from(_: Version<N>) -> Self {
28        N
29    }
30}
31
32impl<const N: u8> Display for Version<N> {
33    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
34        write!(f, "{N}")
35    }
36}
37
38impl<const N: u8> Serialize for Version<N> {
39    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
40        serializer.serialize_u8(N)
41    }
42}
43
44impl<'de, const N: u8> Deserialize<'de> for Version<N> {
45    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
46        let v = u8::deserialize(deserializer)?;
47        if v == N {
48            Ok(Self)
49        } else {
50            Err(serde::de::Error::custom(format!(
51                "expected protocol version {N}, got {v}"
52            )))
53        }
54    }
55}
56
57/// Type alias for the x402 v2 version marker.
58pub type Version2 = Version<2>;
59
60/// Singleton value for [`Version2`].
61pub const V2: Version2 = Version;