1use std::str::FromStr;
2
3use serde::Deserialize;
4use xmlserde::XmlValue;
5
6#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
7pub struct Version(u16, Option<u16>, Option<u16>);
8
9impl Version {
10 pub fn new(major: u16, minor: u16, patch: u16) -> Self {
11 Self(major, Some(minor), Some(patch))
12 }
13
14 pub fn major(self) -> u16 {
15 self.0
16 }
17
18 pub fn minor(self) -> Option<u16> {
19 self.1
20 }
21
22 pub fn patch(self) -> Option<u16> {
23 self.2
24 }
25}
26
27impl<'de> Deserialize<'de> for Version {
28 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
29 where
30 D: serde::Deserializer<'de>,
31 {
32 let str = <String as Deserialize>::deserialize(deserializer)?;
33 Self::from_str(&str).map_err(serde::de::Error::custom)
34 }
35}
36
37impl FromStr for Version {
38 type Err = String;
39
40 fn from_str(s: &str) -> Result<Self, String> {
43 if s.contains('.') {
44 let mut parts = s
45 .splitn(4, '.')
46 .map(str::parse)
47 .take_while(Result::is_ok)
48 .map(Result::unwrap);
49 Ok(Self(parts.next().unwrap_or(0), parts.next(), parts.next()))
50 } else {
51 let val = s.parse::<u16>();
52 Ok(Self(val.unwrap_or(0), None, None))
53 }
54 }
55}
56
57impl XmlValue for Version {
58 fn serialize(&self) -> String {
59 self.to_string()
60 }
61
62 fn deserialize(s: &str) -> Result<Self, String> {
63 Self::from_str(s)
64 }
65}
66
67impl std::fmt::Display for Version {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
69 match *self {
70 Self(major, None, None) => write!(f, "{major}"),
71 Self(major, Some(minor), None) => write!(f, "{major}.{minor}"),
72 Self(major, None, Some(patch)) => write!(f, "{major}.0.{patch}"),
73 Self(major, Some(minor), Some(patch)) => write!(f, "{major}.{minor}.{patch}"),
74 }
75 }
76}
77
78impl PartialEq<str> for Version {
79 fn eq(&self, other: &str) -> bool {
80 self.to_string() == other
81 }
82}