agent_client_protocol/
version.rs1use schemars::JsonSchema;
2use serde::Serialize;
3
4pub const V0: ProtocolVersion = ProtocolVersion(0);
5pub const V1: ProtocolVersion = ProtocolVersion(1);
6pub const VERSION: ProtocolVersion = V1;
7
8#[derive(Default, Debug, Clone, Serialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)]
13pub struct ProtocolVersion(u16);
14
15impl ProtocolVersion {
16 #[cfg(test)]
17 pub const fn new(version: u16) -> Self {
18 Self(version)
19 }
20}
21
22use serde::{Deserialize, Deserializer};
23
24impl<'de> Deserialize<'de> for ProtocolVersion {
25 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
26 where
27 D: Deserializer<'de>,
28 {
29 use serde::de::{self, Visitor};
30 use std::fmt;
31
32 struct ProtocolVersionVisitor;
33
34 impl<'de> Visitor<'de> for ProtocolVersionVisitor {
35 type Value = ProtocolVersion;
36
37 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
38 formatter.write_str("a protocol version number or string")
39 }
40
41 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
42 where
43 E: de::Error,
44 {
45 if value <= u16::MAX as u64 {
46 Ok(ProtocolVersion(value as u16))
47 } else {
48 Err(E::custom(format!("protocol version {value} is too large")))
49 }
50 }
51
52 fn visit_str<E>(self, _value: &str) -> Result<Self::Value, E>
53 where
54 E: de::Error,
55 {
56 Ok(ProtocolVersion(0))
58 }
59
60 fn visit_string<E>(self, _value: String) -> Result<Self::Value, E>
61 where
62 E: de::Error,
63 {
64 Ok(ProtocolVersion(0))
66 }
67 }
68
69 deserializer.deserialize_any(ProtocolVersionVisitor)
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76
77 #[test]
78 fn test_deserialize_u64() {
79 let json = "1";
80 let version: ProtocolVersion = serde_json::from_str(json).unwrap();
81 assert_eq!(version, ProtocolVersion::new(1));
82 }
83
84 #[test]
85 fn test_deserialize_string() {
86 let json = "\"1.0.0\"";
87 let version: ProtocolVersion = serde_json::from_str(json).unwrap();
88 assert_eq!(version, ProtocolVersion::new(0));
89 }
90
91 #[test]
92 fn test_deserialize_large_number() {
93 let json = "100000";
94 let result: Result<ProtocolVersion, _> = serde_json::from_str(json);
95 assert!(result.is_err());
96 }
97
98 #[test]
99 fn test_deserialize_zero() {
100 let json = "0";
101 let version: ProtocolVersion = serde_json::from_str(json).unwrap();
102 assert_eq!(version, ProtocolVersion::new(0));
103 }
104
105 #[test]
106 fn test_deserialize_max_u16() {
107 let json = "65535";
108 let version: ProtocolVersion = serde_json::from_str(json).unwrap();
109 assert_eq!(version, ProtocolVersion::new(65535));
110 }
111}