gir_parser/
version.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::str::FromStr;

use serde::Deserialize;
use xmlserde::XmlValue;

#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version(u16, Option<u16>, Option<u16>);

impl Version {
    pub fn new(major: u16, minor: u16, patch: u16) -> Self {
        Self(major, Some(minor), Some(patch))
    }

    pub fn major(self) -> u16 {
        self.0
    }

    pub fn minor(self) -> Option<u16> {
        self.1
    }

    pub fn patch(self) -> Option<u16> {
        self.2
    }
}

impl<'de> Deserialize<'de> for Version {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let str = <String as Deserialize>::deserialize(deserializer)?;
        Self::from_str(&str).map_err(serde::de::Error::custom)
    }
}

impl FromStr for Version {
    type Err = String;

    /// Parse a `Version` from a string.
    /// Currently always return Ok
    fn from_str(s: &str) -> Result<Self, String> {
        if s.contains('.') {
            let mut parts = s
                .splitn(4, '.')
                .map(str::parse)
                .take_while(Result::is_ok)
                .map(Result::unwrap);
            Ok(Self(parts.next().unwrap_or(0), parts.next(), parts.next()))
        } else {
            let val = s.parse::<u16>();
            Ok(Self(val.unwrap_or(0), None, None))
        }
    }
}

impl XmlValue for Version {
    fn serialize(&self) -> String {
        self.to_string()
    }

    fn deserialize(s: &str) -> Result<Self, String> {
        Self::from_str(s)
    }
}

impl std::fmt::Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        match *self {
            Self(major, None, None) => write!(f, "{major}"),
            Self(major, Some(minor), None) => write!(f, "{major}.{minor}"),
            Self(major, None, Some(patch)) => write!(f, "{major}.0.{patch}"),
            Self(major, Some(minor), Some(patch)) => write!(f, "{major}.{minor}.{patch}"),
        }
    }
}

impl PartialEq<str> for Version {
    fn eq(&self, other: &str) -> bool {
        self.to_string() == other
    }
}