1use std::{
2 fmt::{self, Display},
3 str::FromStr,
4};
5
6use anyhow::{anyhow, Result};
7use serde::{de::Error, Deserialize, Serialize};
8
9/// A datastructure representing a semantic version number
10#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
11pub struct SemanticVersion {
12 pub major: usize,
13 pub minor: usize,
14 pub patch: usize,
15}
16
17pub fn semver(major: usize, minor: usize, patch: usize) -> SemanticVersion {
18 SemanticVersion {
19 major,
20 minor,
21 patch,
22 }
23}
24
25impl SemanticVersion {
26 pub fn new(major: usize, minor: usize, patch: usize) -> Self {
27 Self {
28 major,
29 minor,
30 patch,
31 }
32 }
33}
34
35impl FromStr for SemanticVersion {
36 type Err = anyhow::Error;
37 fn from_str(s: &str) -> Result<Self> {
38 let mut components = s.trim().split('.');
39 let major = components
40 .next()
41 .ok_or_else(|| anyhow!("missing major version number"))?
42 .parse()?;
43 let minor = components
44 .next()
45 .ok_or_else(|| anyhow!("missing minor version number"))?
46 .parse()?;
47 let patch = components
48 .next()
49 .ok_or_else(|| anyhow!("missing patch version number"))?
50 .parse()?;
51 Ok(Self {
52 major,
53 minor,
54 patch,
55 })
56 }
57}
58
59impl Display for SemanticVersion {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
62 }
63}
64
65impl Serialize for SemanticVersion {
66 fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
67 where
68 S: serde::Serializer,
69 {
70 serializer.serialize_str(&self.to_string())
71 }
72}
73
74impl<'de> Deserialize<'de> for SemanticVersion {
75 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
76 where
77 D: serde::Deserializer<'de>,
78 {
79 let string = String::deserialize(deserializer)?;
80 Self::from_str(&string)
81 .map_err(|_| Error::custom(format!("Invalid version string \"{string}\"")))
82 }
83}