1use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
4use std::fmt;
5
6pub const PROTOCOL_VERSION: Version = Version { major: 0, minor: 2 };
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct Version {
18 pub major: u16,
20 pub minor: u16,
22}
23
24impl Version {
25 pub const fn new(major: u16, minor: u16) -> Self {
27 Self { major, minor }
28 }
29
30 pub const fn is_compatible_with(self, other: Version) -> bool {
35 self.major == other.major
36 }
37}
38
39impl fmt::Display for Version {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 write!(f, "{}.{}", self.major, self.minor)
42 }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
47#[error("malformed protocol version {0:?}, expected \"major.minor\"")]
48pub struct VersionParseError(pub String);
49
50impl std::str::FromStr for Version {
51 type Err = VersionParseError;
52
53 fn from_str(s: &str) -> Result<Self, Self::Err> {
54 let err = || VersionParseError(s.to_owned());
55 let (major, minor) = s.split_once('.').ok_or_else(err)?;
56 Ok(Self {
57 major: major.parse().map_err(|_| err())?,
58 minor: minor.parse().map_err(|_| err())?,
59 })
60 }
61}
62
63impl Serialize for Version {
64 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
65 s.collect_str(self)
66 }
67}
68
69impl<'de> Deserialize<'de> for Version {
70 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
71 let raw = String::deserialize(d)?;
72 raw.parse().map_err(D::Error::custom)
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 #[test]
81 fn round_trips_as_a_string() {
82 let json = serde_json::to_string(&PROTOCOL_VERSION).unwrap();
83 assert_eq!(json, r#""0.2""#);
84 assert_eq!(
85 serde_json::from_str::<Version>(&json).unwrap(),
86 PROTOCOL_VERSION
87 );
88 }
89
90 #[test]
91 fn minor_differences_stay_compatible() {
92 assert!(Version::new(0, 7).is_compatible_with(PROTOCOL_VERSION));
93 assert!(Version::new(0, 0).is_compatible_with(PROTOCOL_VERSION));
94 assert!(!Version::new(1, 0).is_compatible_with(PROTOCOL_VERSION));
95 }
96
97 #[test]
98 fn rejects_malformed_versions() {
99 for bad in ["", "1", "1.", ".1", "x.y", "0.1.2"] {
100 assert!(bad.parse::<Version>().is_err(), "{bad:?} should not parse");
101 }
102 }
103}