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
use std::fmt::{self, Debug, Display, Formatter};
use std::str::FromStr;

use anyhow::{format_err, Error, Result};
use semver::Version;

#[derive(Copy, Clone, Eq, PartialEq)]
pub enum ApiVersion {
    V1_0_0,
    V1_1_0,
}

impl ApiVersion {
    pub fn as_semver(&self) -> Version {
        match self {
            ApiVersion::V1_0_0 => Version::new(1, 0, 0),
            ApiVersion::V1_1_0 => Version::new(1, 1, 0),
        }
    }
}

impl Debug for ApiVersion {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let semver = self.as_semver();
        write!(f, "{}.{}.{}", semver.major, semver.minor, semver.patch)
    }
}

impl Display for ApiVersion {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let semver = self.as_semver();
        write!(f, "{}.{}.{}", semver.major, semver.minor, semver.patch)
    }
}

impl FromStr for ApiVersion {
    type Err = Error;
    fn from_str(api_version_str: &str) -> Result<Self> {
        let api_version = Version::parse(api_version_str)?;
        match (api_version.major, api_version.minor, api_version.patch) {
            (1, 0, 0) => Ok(ApiVersion::V1_0_0),
            (1, 1, 0) => Ok(ApiVersion::V1_1_0),
            (1, 1, _) | (1, 0, _) => Err(format_err!(
                "Could not parse API Version from string (patch)"
            )),
            (1, _, _) => Err(format_err!(
                "Could not parse API Version from string (minor)"
            )),
            _ => Err(format_err!(
                "Could not parse API Version from string (major)"
            )),
        }
    }
}

#[test]
fn test_fmt() {
    assert_eq!(format!("{}", ApiVersion::V1_0_0), "1.0.0");
    assert_eq!(format!("{}", ApiVersion::V1_1_0), "1.1.0");
}

#[test]
fn test_as_semver() {
    assert_eq!(ApiVersion::V1_0_0.as_semver().major, 1);
    assert_eq!(ApiVersion::V1_1_0.as_semver().major, 1);
}