1use std::cmp::Ordering;
5use std::fmt;
6use std::str::FromStr;
7
8use crate::{Error, Result};
9
10#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
18pub struct Version {
19 pub major: u32,
21 pub minor: u32,
23 pub build: Option<u32>,
25 pub revision: Option<u32>,
27}
28
29impl Version {
30 pub const fn new(major: u32, minor: u32) -> Self {
32 Self {
33 major,
34 minor,
35 build: None,
36 revision: None,
37 }
38 }
39
40 pub const fn new_with_build(major: u32, minor: u32, build: u32) -> Self {
42 Self {
43 major,
44 minor,
45 build: Some(build),
46 revision: None,
47 }
48 }
49
50 pub const fn new_with_revision(major: u32, minor: u32, build: u32, revision: u32) -> Self {
52 Self {
53 major,
54 minor,
55 build: Some(build),
56 revision: Some(revision),
57 }
58 }
59
60 pub fn from_system_version_parts(
63 major: i32,
64 minor: i32,
65 build: i32,
66 revision: i32,
67 ) -> Result<Self> {
68 if major < 0 || minor < 0 || build < -1 || revision < -1 || (build == -1 && revision != -1)
69 {
70 return Err(Error::InvalidFormat(
71 "Version components must be non-negative, except that build and revision may be -1."
72 .to_owned(),
73 ));
74 }
75
76 Ok(match (build, revision) {
77 (-1, -1) => Self::new(major as u32, minor as u32),
78 (build, -1) => Self::new_with_build(major as u32, minor as u32, build as u32),
79 (build, revision) => {
80 Self::new_with_revision(major as u32, minor as u32, build as u32, revision as u32)
81 }
82 })
83 }
84
85 pub const fn build_or_unspecified(self) -> i64 {
88 match self.build {
89 Some(value) => value as i64,
90 None => -1,
91 }
92 }
93
94 pub const fn revision_or_unspecified(self) -> i64 {
97 match self.revision {
98 Some(value) => value as i64,
99 None => -1,
100 }
101 }
102
103 pub fn ensure_non_negative_components(self, field_count: usize) -> Result<Self> {
109 if field_count > 4 {
110 return Err(Error::InvalidOperation(
111 "The field count must be between 0 and 4.".to_owned(),
112 ));
113 }
114
115 let build = if field_count >= 3 {
116 Some(self.build.unwrap_or(0))
117 } else {
118 self.build
119 };
120 let revision = if field_count >= 4 {
121 Some(self.revision.unwrap_or(0))
122 } else {
123 self.revision
124 };
125
126 Ok(Self {
127 build,
128 revision,
129 ..self
130 })
131 }
132
133 pub fn to_string_safe(self, field_count: usize) -> Result<String> {
138 if field_count > 4 {
139 return Err(Error::InvalidOperation(
140 "The field count must be between 0 and 4.".to_owned(),
141 ));
142 }
143
144 let version = self.ensure_non_negative_components(field_count)?;
145 let mut fields = [
146 version.major,
147 version.minor,
148 version.build.unwrap_or(0),
149 version.revision.unwrap_or(0),
150 ]
151 .into_iter();
152 Ok((0..field_count)
153 .map(|_| fields.next().expect("field count is bounded").to_string())
154 .collect::<Vec<_>>()
155 .join("."))
156 }
157
158 pub const fn component_count(self) -> usize {
160 if self.revision.is_some() {
161 4
162 } else if self.build.is_some() {
163 3
164 } else {
165 2
166 }
167 }
168}
169
170impl Default for Version {
171 fn default() -> Self {
172 Self::new(0, 0)
173 }
174}
175
176impl fmt::Display for Version {
177 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
178 write!(formatter, "{}.{}", self.major, self.minor)?;
179 if let Some(build) = self.build {
180 write!(formatter, ".{build}")?;
181 }
182 if let Some(revision) = self.revision {
183 write!(formatter, ".{revision}")?;
184 }
185
186 Ok(())
187 }
188}
189
190impl FromStr for Version {
191 type Err = Error;
192
193 fn from_str(value: &str) -> Result<Self> {
194 let fields: Vec<_> = value.split('.').collect();
195 if !(2..=4).contains(&fields.len())
196 || fields
197 .iter()
198 .any(|field| field.is_empty() || !field.bytes().all(|byte| byte.is_ascii_digit()))
199 {
200 return Err(Error::InvalidFormat(format!(
201 "'{value}' is not a two- to four-component version."
202 )));
203 }
204
205 let parse = |field: &str| {
206 field.parse::<i32>().map(|value| value as u32).map_err(|_| {
207 Error::InvalidFormat(format!("'{value}' contains an invalid version component."))
208 })
209 };
210 let major = parse(fields[0])?;
211 let minor = parse(fields[1])?;
212 Ok(match fields.len() {
213 2 => Self::new(major, minor),
214 3 => Self::new_with_build(major, minor, parse(fields[2])?),
215 4 => Self::new_with_revision(major, minor, parse(fields[2])?, parse(fields[3])?),
216 _ => unreachable!(),
217 })
218 }
219}
220
221impl Ord for Version {
222 fn cmp(&self, other: &Self) -> Ordering {
223 (
224 self.major,
225 self.minor,
226 self.build_or_unspecified(),
227 self.revision_or_unspecified(),
228 )
229 .cmp(&(
230 other.major,
231 other.minor,
232 other.build_or_unspecified(),
233 other.revision_or_unspecified(),
234 ))
235 }
236}
237
238impl PartialOrd for Version {
239 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
240 Some(self.cmp(other))
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn parses_and_displays_two_to_four_components() {
250 for text in ["1.2", "1.2.3", "1.2.3.4"] {
251 let version: Version = text.parse().unwrap();
252 assert_eq!(text, version.to_string());
253 assert_eq!(text.split('.').count(), version.component_count());
254 }
255 }
256
257 #[test]
258 fn rejects_invalid_versions() {
259 for text in ["", "1", "1.", "1.2.", "1.2.3.4.5", "-1.2", "1. 2"] {
260 assert!(text.parse::<Version>().is_err(), "{text}");
261 }
262 }
263
264 #[test]
265 fn unspecified_components_affect_equality_and_ordering() {
266 assert_ne!(Version::new(1, 2), Version::new_with_build(1, 2, 0));
267 assert!(Version::new(1, 2) < Version::new_with_build(1, 2, 0));
268 assert!(Version::new_with_build(1, 2, 3) < Version::new_with_revision(1, 2, 3, 0));
269 }
270
271 #[test]
272 fn safe_format_fills_unspecified_components() {
273 let version = Version::new(1, 2);
274 assert_eq!("", version.to_string_safe(0).unwrap());
275 assert_eq!("1", version.to_string_safe(1).unwrap());
276 assert_eq!("1.2", version.to_string_safe(2).unwrap());
277 assert_eq!("1.2.0", version.to_string_safe(3).unwrap());
278 assert_eq!("1.2.0.0", version.to_string_safe(4).unwrap());
279 assert!(version.to_string_safe(5).is_err());
280 }
281
282 #[test]
283 fn creates_from_system_version_parts() {
284 assert_eq!(
285 Version::new(1, 2),
286 Version::from_system_version_parts(1, 2, -1, -1).unwrap()
287 );
288 assert!(Version::from_system_version_parts(1, 2, -1, 0).is_err());
289 }
290}