semantic_version.rs

 1use std::{
 2    fmt::{self, Display},
 3    str::FromStr,
 4};
 5
 6use anyhow::{anyhow, Result};
 7use serde::Serialize;
 8
 9/// A datastructure representing a semantic version number
10#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize)]
11pub struct SemanticVersion {
12    pub major: usize,
13    pub minor: usize,
14    pub patch: usize,
15}
16
17impl SemanticVersion {
18    pub fn new(major: usize, minor: usize, patch: usize) -> Self {
19        Self {
20            major,
21            minor,
22            patch,
23        }
24    }
25}
26
27impl FromStr for SemanticVersion {
28    type Err = anyhow::Error;
29    fn from_str(s: &str) -> Result<Self> {
30        let mut components = s.trim().split('.');
31        let major = components
32            .next()
33            .ok_or_else(|| anyhow!("missing major version number"))?
34            .parse()?;
35        let minor = components
36            .next()
37            .ok_or_else(|| anyhow!("missing minor version number"))?
38            .parse()?;
39        let patch = components
40            .next()
41            .ok_or_else(|| anyhow!("missing patch version number"))?
42            .parse()?;
43        Ok(Self {
44            major,
45            minor,
46            patch,
47        })
48    }
49}
50
51impl Display for SemanticVersion {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
54    }
55}