Skip to main content

arin_protocol/
version.rs

1//! Protocol version, carried on every message as `v`.
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
4use std::fmt;
5
6/// The protocol version this build speaks.
7pub const PROTOCOL_VERSION: Version = Version { major: 0, minor: 1 };
8
9/// A `major.minor` protocol version.
10///
11/// Serialized as a string, for example `"0.1"`. Patch numbers do not exist here: the
12/// protocol only changes in ways that matter at the minor level or above.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Version {
15    /// Breaking-change generation. A mismatch is unrecoverable.
16    pub major: u16,
17    /// Additive revision within a major. Higher minors stay readable by lower ones.
18    pub minor: u16,
19}
20
21impl Version {
22    /// Construct a version.
23    pub const fn new(major: u16, minor: u16) -> Self {
24        Self { major, minor }
25    }
26
27    /// Whether a peer speaking `self` can be understood by an implementation of `other`.
28    ///
29    /// Majors must match exactly. Minors may differ in either direction, because unknown
30    /// fields are ignored and changes within a major are additive.
31    pub const fn is_compatible_with(self, other: Version) -> bool {
32        self.major == other.major
33    }
34}
35
36impl fmt::Display for Version {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(f, "{}.{}", self.major, self.minor)
39    }
40}
41
42/// Returned when a `v` field is not a `major.minor` pair.
43#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
44#[error("malformed protocol version {0:?}, expected \"major.minor\"")]
45pub struct VersionParseError(pub String);
46
47impl std::str::FromStr for Version {
48    type Err = VersionParseError;
49
50    fn from_str(s: &str) -> Result<Self, Self::Err> {
51        let err = || VersionParseError(s.to_owned());
52        let (major, minor) = s.split_once('.').ok_or_else(err)?;
53        Ok(Self {
54            major: major.parse().map_err(|_| err())?,
55            minor: minor.parse().map_err(|_| err())?,
56        })
57    }
58}
59
60impl Serialize for Version {
61    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
62        s.collect_str(self)
63    }
64}
65
66impl<'de> Deserialize<'de> for Version {
67    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
68        let raw = String::deserialize(d)?;
69        raw.parse().map_err(D::Error::custom)
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    #[test]
78    fn round_trips_as_a_string() {
79        let json = serde_json::to_string(&PROTOCOL_VERSION).unwrap();
80        assert_eq!(json, r#""0.1""#);
81        assert_eq!(
82            serde_json::from_str::<Version>(&json).unwrap(),
83            PROTOCOL_VERSION
84        );
85    }
86
87    #[test]
88    fn minor_differences_stay_compatible() {
89        assert!(Version::new(0, 7).is_compatible_with(PROTOCOL_VERSION));
90        assert!(Version::new(0, 0).is_compatible_with(PROTOCOL_VERSION));
91        assert!(!Version::new(1, 0).is_compatible_with(PROTOCOL_VERSION));
92    }
93
94    #[test]
95    fn rejects_malformed_versions() {
96        for bad in ["", "1", "1.", ".1", "x.y", "0.1.2"] {
97            assert!(bad.parse::<Version>().is_err(), "{bad:?} should not parse");
98        }
99    }
100}