karyon_p2p/
version.rs

1use std::str::FromStr;
2
3use bincode::{Decode, Encode};
4use semver::VersionReq;
5
6use crate::{Error, Result};
7
8/// Represents the network version and protocol version used in karyon p2p.
9///
10/// # Example
11///
12/// ```
13/// use karyon_p2p::Version;
14///
15/// let version: Version = "0.2.0, >0.1.0".parse().unwrap();
16///
17/// let version: Version = "0.2.0".parse().unwrap();
18///
19/// ```
20#[derive(Debug, Clone)]
21pub struct Version {
22    pub v: VersionInt,
23    pub req: VersionReq,
24}
25
26impl Version {
27    /// Creates a new Version
28    pub fn new(v: VersionInt, req: VersionReq) -> Self {
29        Self { v, req }
30    }
31}
32
33#[derive(Debug, Decode, Encode, Clone)]
34pub struct VersionInt {
35    major: u64,
36    minor: u64,
37    patch: u64,
38}
39
40impl FromStr for Version {
41    type Err = Error;
42
43    fn from_str(s: &str) -> Result<Self> {
44        let v: Vec<&str> = s.split(", ").collect();
45        if v.is_empty() || v.len() > 2 {
46            return Err(Error::ParseError(format!("Invalid version{s}")));
47        }
48
49        let version: VersionInt = v[0].parse()?;
50        let req: VersionReq = if v.len() > 1 { v[1] } else { v[0] }.parse()?;
51
52        Ok(Self { v: version, req })
53    }
54}
55
56impl FromStr for VersionInt {
57    type Err = Error;
58
59    fn from_str(s: &str) -> Result<Self> {
60        let v: Vec<&str> = s.split('.').collect();
61        if v.len() < 2 || v.len() > 3 {
62            return Err(Error::ParseError(format!("Invalid version{s}")));
63        }
64
65        let major = v[0].parse::<u64>()?;
66        let minor = v[1].parse::<u64>()?;
67        let patch = v.get(2).unwrap_or(&"0").parse::<u64>()?;
68
69        Ok(Self {
70            major,
71            minor,
72            patch,
73        })
74    }
75}
76
77impl std::fmt::Display for VersionInt {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
80    }
81}
82
83impl From<VersionInt> for semver::Version {
84    fn from(v: VersionInt) -> Self {
85        semver::Version::new(v.major, v.minor, v.patch)
86    }
87}
88
89/// Check if a version satisfies a version request.
90pub fn version_match(version_req: &VersionReq, version: &VersionInt) -> bool {
91    let version: semver::Version = version.clone().into();
92    version_req.matches(&version)
93}