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.
7///
8/// 0.2 added `arrow`. A 0.1 peer keeps working: majors match, and an older daemon
9/// answers the one message it does not know with an error rather than closing.
10pub const PROTOCOL_VERSION: Version = Version { major: 0, minor: 2 };
11
12/// A `major.minor` protocol version.
13///
14/// Serialized as a string, for example `"0.1"`. Patch numbers do not exist here: the
15/// protocol only changes in ways that matter at the minor level or above.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct Version {
18    /// Breaking-change generation. A mismatch is unrecoverable.
19    pub major: u16,
20    /// Additive revision within a major. Higher minors stay readable by lower ones.
21    pub minor: u16,
22}
23
24impl Version {
25    /// Construct a version.
26    pub const fn new(major: u16, minor: u16) -> Self {
27        Self { major, minor }
28    }
29
30    /// Whether a peer speaking `self` can be understood by an implementation of `other`.
31    ///
32    /// Majors must match exactly. Minors may differ in either direction, because unknown
33    /// fields are ignored and changes within a major are additive.
34    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/// Returned when a `v` field is not a `major.minor` pair.
46#[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}