1use crate::error::*;
2use std::str::FromStr;
3
4#[derive(Copy, Clone, Eq, Debug)]
5pub struct Version {
6 pub major: u64,
7 pub minor: u64,
8}
9
10impl Version {
11 #[allow(dead_code)]
12 pub fn new(major: u64, minor: u64) -> Self {
13 Self { major, minor }
14 }
15}
16
17impl FromStr for Version {
18 type Err = Error;
19 fn from_str(s: &str) -> Result<Version> {
20 let vv = s.split('.').collect::<Vec<&str>>();
21 match (vv.first(), vv.get(1)) {
22 (Some(maj), Some(min)) => Ok(Version {
23 major: maj.parse()?,
24 minor: min.parse()?,
25 }),
26 _ => Err(ErrorKind::SpecVersion(s.into()).into()),
27 }
28 }
29}
30
31use std::cmp;
32
33impl PartialOrd for Version {
34 fn partial_cmp(&self, other: &Version) -> Option<cmp::Ordering> {
35 Some(self.cmp(other))
36 }
37}
38
39impl PartialEq for Version {
40 fn eq(&self, other: &Version) -> bool {
41 self.major == other.major && self.minor == other.minor
42 }
43}
44
45impl Ord for Version {
46 fn cmp(&self, other: &Version) -> cmp::Ordering {
47 match self.major.cmp(&other.major) {
48 cmp::Ordering::Equal => {}
49 r => return r,
50 }
51 match self.minor.cmp(&other.minor) {
52 cmp::Ordering::Equal => {}
53 r => return r,
54 }
55 cmp::Ordering::Equal
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn version_parsing() {
65 assert_eq!("1.3".parse::<Version>().unwrap(), Version::new(1, 3));
66 }
67
68 #[test]
69 fn version_comparison() {
70 assert!(Version::new(1, 3) >= Version::new(1, 2));
71 assert!(Version::new(1, 2) >= Version::new(1, 2));
72 assert!(Version::new(1, 2) == Version::new(1, 2));
73 assert!(Version::new(1, 1) <= Version::new(1, 2));
74 }
75}