Skip to main content

armillae_simulate/
version.rs

1use std::{
2    borrow::Cow,
3    cmp::Ordering,
4    fmt,
5    hash::{Hash, Hasher},
6    str::FromStr,
7};
8
9use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
10use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum VersionKind {
15    SemanticVersion,
16    Requirement,
17}
18
19#[derive(Clone, Debug, thiserror::Error)]
20#[error("invalid {kind:?}: {message}")]
21pub struct InvalidVersion {
22    pub kind: VersionKind,
23    pub message: String,
24}
25
26#[derive(Clone, Debug)]
27pub struct SemanticVersion {
28    canonical: String,
29    parsed: semver::Version,
30}
31
32impl SemanticVersion {
33    pub fn new(value: impl Into<String>) -> Result<Self, InvalidVersion> {
34        let value = value.into();
35        let parsed = semver::Version::parse(&value).map_err(|error| InvalidVersion {
36            kind: VersionKind::SemanticVersion,
37            message: error.to_string(),
38        })?;
39        Ok(Self {
40            canonical: parsed.to_string(),
41            parsed,
42        })
43    }
44
45    pub fn as_str(&self) -> &str {
46        &self.canonical
47    }
48}
49
50#[derive(Clone, Debug)]
51pub struct VersionRequirement {
52    canonical: String,
53    parsed: semver::VersionReq,
54}
55
56impl VersionRequirement {
57    pub fn new(value: impl Into<String>) -> Result<Self, InvalidVersion> {
58        let value = value.into();
59        let parsed = semver::VersionReq::parse(&value).map_err(|error| InvalidVersion {
60            kind: VersionKind::Requirement,
61            message: error.to_string(),
62        })?;
63        Ok(Self {
64            canonical: parsed.to_string(),
65            parsed,
66        })
67    }
68
69    pub fn as_str(&self) -> &str {
70        &self.canonical
71    }
72
73    pub fn matches(&self, version: &SemanticVersion) -> bool {
74        self.parsed.matches(&version.parsed)
75    }
76}
77
78macro_rules! impl_version_value {
79    ($name:ident, $schema_name:literal, $schema_id:literal, $schema:expr) => {
80        impl PartialEq for $name {
81            fn eq(&self, other: &Self) -> bool {
82                self.canonical == other.canonical
83            }
84        }
85
86        impl Eq for $name {}
87
88        impl PartialOrd for $name {
89            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
90                Some(self.cmp(other))
91            }
92        }
93
94        impl Ord for $name {
95            fn cmp(&self, other: &Self) -> Ordering {
96                self.canonical.cmp(&other.canonical)
97            }
98        }
99
100        impl Hash for $name {
101            fn hash<H: Hasher>(&self, state: &mut H) {
102                self.canonical.hash(state);
103            }
104        }
105
106        impl AsRef<str> for $name {
107            fn as_ref(&self) -> &str {
108                self.as_str()
109            }
110        }
111
112        impl fmt::Display for $name {
113            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
114                formatter.write_str(self.as_str())
115            }
116        }
117
118        impl FromStr for $name {
119            type Err = InvalidVersion;
120
121            fn from_str(value: &str) -> Result<Self, Self::Err> {
122                Self::new(value)
123            }
124        }
125
126        impl Serialize for $name {
127            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
128            where
129                S: Serializer,
130            {
131                serializer.serialize_str(self.as_str())
132            }
133        }
134
135        impl<'de> Deserialize<'de> for $name {
136            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
137            where
138                D: Deserializer<'de>,
139            {
140                let value = String::deserialize(deserializer)?;
141                Self::new(value).map_err(de::Error::custom)
142            }
143        }
144
145        impl JsonSchema for $name {
146            fn schema_name() -> Cow<'static, str> {
147                $schema_name.into()
148            }
149
150            fn schema_id() -> Cow<'static, str> {
151                $schema_id.into()
152            }
153
154            fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
155                $schema
156            }
157        }
158    };
159}
160
161impl_version_value!(
162    SemanticVersion,
163    "SemanticVersion",
164    "armillae_simulate::SemanticVersion",
165    json_schema!({
166        "type": "string",
167        "pattern": r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"
168    })
169);
170
171impl_version_value!(
172    VersionRequirement,
173    "VersionRequirement",
174    "armillae_simulate::VersionRequirement",
175    json_schema!({ "type": "string" })
176);