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 FromStr for SemanticVersion {
18 type Err = anyhow::Error;
19
20 fn from_str(s: &str) -> Result<Self> {
21 let mut components = s.trim().split('.');
22 let major = components
23 .next()
24 .ok_or_else(|| anyhow!("missing major version number"))?
25 .parse()?;
26 let minor = components
27 .next()
28 .ok_or_else(|| anyhow!("missing minor version number"))?
29 .parse()?;
30 let patch = components
31 .next()
32 .ok_or_else(|| anyhow!("missing patch version number"))?
33 .parse()?;
34 Ok(Self {
35 major,
36 minor,
37 patch,
38 })
39 }
40}
41
42impl Display for SemanticVersion {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
45 }
46}