1use std::borrow::Cow;
8use std::fmt;
9use std::str::FromStr;
10
11use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
12use serde::{Deserialize, Serialize};
13
14#[cfg(test)]
15mod tests;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
19#[serde(try_from = "String", into = "String")]
20pub struct SchedrVersion {
21 pub major: u32,
23 pub minor: u32,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
29#[error("`{0}` is not a schedr version (expected `major.minor` or `major.minor.patch`)")]
30pub struct VersionError(pub String);
31
32impl SchedrVersion {
33 #[must_use]
35 pub const fn new(major: u32, minor: u32) -> Self {
36 Self { major, minor }
37 }
38
39 #[must_use]
45 pub fn current() -> Self {
46 env!("CARGO_PKG_VERSION")
47 .parse()
48 .expect("the crate version is a valid schedr version")
49 }
50
51 #[must_use]
54 pub const fn can_read(self, produced: Self) -> bool {
55 self.major == produced.major && produced.minor <= self.minor
56 }
57}
58
59impl fmt::Display for SchedrVersion {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "{}.{}", self.major, self.minor)
62 }
63}
64
65impl FromStr for SchedrVersion {
66 type Err = VersionError;
67
68 fn from_str(s: &str) -> Result<Self, Self::Err> {
71 let error = || VersionError(s.to_owned());
72 let mut parts = s.split('.');
73 let major = parts
74 .next()
75 .and_then(|p| p.parse().ok())
76 .ok_or_else(error)?;
77 let minor = parts
78 .next()
79 .and_then(|p| p.parse().ok())
80 .ok_or_else(error)?;
81 match (parts.next(), parts.next()) {
82 (None, None) => {}
83 (Some(patch), None) if !patch.is_empty() => {}
84 _ => return Err(error()),
85 }
86 Ok(Self { major, minor })
87 }
88}
89
90impl TryFrom<String> for SchedrVersion {
91 type Error = VersionError;
92
93 fn try_from(s: String) -> Result<Self, Self::Error> {
94 s.parse()
95 }
96}
97
98impl From<SchedrVersion> for String {
99 fn from(v: SchedrVersion) -> Self {
100 v.to_string()
101 }
102}
103
104impl JsonSchema for SchedrVersion {
105 fn schema_name() -> Cow<'static, str> {
106 "SchedrVersion".into()
107 }
108
109 fn json_schema(_: &mut SchemaGenerator) -> Schema {
110 json_schema!({
111 "type": "string",
112 "pattern": r"^[0-9]+\.[0-9]+$",
113 "description": "A schedr version as `major.minor`.",
114 })
115 }
116}