editorconfig_core/
version.rs

1use std::fmt::Display;
2use std::str::FromStr;
3
4#[derive(Debug, PartialEq, Eq, Clone, Copy)]
5pub struct Version {
6    pub major: u32,
7    pub minor: u32,
8    pub patch: u32,
9}
10
11impl Display for Version {
12    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
14    }
15}
16
17impl PartialOrd for Version {
18    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
19        Some(self.cmp(other))
20    }
21}
22
23impl Ord for Version {
24    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
25        self.major
26            .cmp(&other.major)
27            .then_with(|| self.minor.cmp(&other.minor))
28            .then_with(|| self.patch.cmp(&other.patch))
29    }
30}
31
32impl FromStr for Version {
33    type Err = &'static str;
34
35    fn from_str(s: &str) -> Result<Self, Self::Err> {
36        const E_SEG: &str = "expected three dot-separated segments";
37        const E_INT: &str = "expected segments to be unsigned integers";
38
39        let mut segs = s.splitn(3, '.');
40        let mut next = || segs.next().ok_or(E_SEG)?.parse().map_err(|_| E_INT);
41
42        Ok(Self { major: next()?, minor: next()?, patch: next()? })
43    }
44}