Debian Codegraph @

third_party/rust/firefox-versioning/src/version.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5 //! ## Firefox Version Comparison
6 //! This module was ported from the Firefox Desktop implementation. You can find the Desktop implementation
7 //! in [this C++ file](https://searchfox.org/mozilla-central/rev/468a65168dd0bc3c7d602211a566c16e66416cce/xpcom/base/nsVersionComparator.cpp)
8 //! There's also some more documentation in the [IDL](https://searchfox.org/mozilla-central/rev/468a65168dd0bc3c7d602211a566c16e66416cce/xpcom/base/nsIVersionComparator.idl#9-31)
9 //!
10 //! ## How versioning works
11 //! This module defines one main struct, the [`Version`] struct. A version is represented by a list of
12 //! dot separated **Version Parts**s. When comparing two versions, we compare each version part in order.
13 //! If one of the versions has a version part, but the other has run out (i.e we have reached the end of the list of version parts)
14 //! we compare the existing version part with the default version part, which is the `0`. For example,
15 //! `1.0` is equivalent to `1.0.0.0`.
16 //!
17 //! For information what version parts are composed of, and how they are compared, read the [next section](#the-version-part).
18 //!
19 //! ### Example Versions
20 //! The following are all valid versions:
21 //! - `1` (one version part, representing the `1`)
22 //! - `` (one version part, representing the empty string, which is equal to `0`)
23 //! - `12+` (one version part, representing `12+` which is equal to `13pre`)
24 //! - `98.1` (two version parts, one representing `98` and another `1`)
25 //! - `98.2pre1.0-beta` (three version parts, one for `98`, one for `2pre1` and one for `0-beta`)
26 //!
27 //!
28 //! ## The Version Part
29 //! A version part is made from 4 elements that directly follow each other:
30 //! - `num_a`: A 32-bit base-10 formatted number that is at the start of the part
31 //! - `str_b`: A non-numeric ascii-encoded string that starts after `num_a`
32 //! - `num_c`: Another 32-bit base-10 formatted number that follows `str_b`
33 //! - `extra_d`: The rest of the version part as an ascii-encoded string
34 //!
35 //! When two version parts are compared, each of `num_a`, `str_b`, `num_c` and `extra_d` are compared
36 //! in order. `num_a` and `num_c` are compared by normal integer comparison, `str_b` and `extra_b` are compared
37 //! by normal byte string comparison.
38 //!
39 //! ### Special values and cases
40 //! There two special characters that can be used in version parts:
41 //! 1. The `*`. This can be used to represent the whole version part. If used, it will set the `num_a` to be
42 //! the maximum value possible ([`i32::MAX`]). This can only be used as the whole version part string. It will parsed
43 //! normally as the `*` ascii character if it is preceded or followed by any other characters.
44 //! 1. The `+`. This can be used as the `str_b`. Whenever a `+` is used as a `str_b`, it increments the `num_a` by 1 and sets
45 //! the `str_b` to be equal to `pre`. For example, `2+` is the same as `3pre`
46 //! 1. An empty `str_b` is always **greater** than a `str_b` with a value. For example, `93` > `93pre`
47 //!
48 //! ## Example version comparisons
49 //! The following comparisons are taken directly from [the brief documentation in Mozilla-Central](https://searchfox.org/mozilla-central/rev/468a65168dd0bc3c7d602211a566c16e66416cce/xpcom/base/nsIVersionComparator.idl#9-31)
50 //! ```
51 //! use firefox_versioning::version::Version;
52 //! let v1 = Version::try_from("1.0pre1").unwrap();
53 //! let v2 = Version::try_from("1.0pre2").unwrap();
54 //! let v3 = Version::try_from("1.0").unwrap();
55 //! let v4 = Version::try_from("1.0.0").unwrap();
56 //! let v5 = Version::try_from("1.0.0.0").unwrap();
57 //! let v6 = Version::try_from("1.1pre").unwrap();
58 //! let v7 = Version::try_from("1.1pre0").unwrap();
59 //! let v8 = Version::try_from("1.0+").unwrap();
60 //! let v9 = Version::try_from("1.1pre1a").unwrap();
61 //! let v10 = Version::try_from("1.1pre1").unwrap();
62 //! let v11 = Version::try_from("1.1pre10a").unwrap();
63 //! let v12 = Version::try_from("1.1pre10").unwrap();
64 //! assert!(v1 < v2);
65 //! assert!(v2 < v3);
66 //! assert!(v3 == v4);
67 //! assert!(v4 == v5);
68 //! assert!(v5 < v6);
69 //! assert!(v6 == v7);
70 //! assert!(v7 == v8);
71 //! assert!(v8 < v9);
72 //! assert!(v9 < v10);
73 //! assert!(v10 < v11);
74 //! assert!(v11 < v12);
75 //! ```
76 //! What the above is comparing is:
77 //! 1.0pre1
78 //! < 1.0pre2
79 //! < 1.0 == 1.0.0 == 1.0.0.0
80 //! < 1.1pre == 1.1pre0 == 1.0+
81 //! < 1.1pre1a
82 //! < 1.1pre1
83 //! < 1.1pre10a
84 //! < 1.1pre10
85
86 use crate::error::VersionParsingError;
87 use std::cmp::Ordering;
88
89 #[derive(Debug, Default, Clone, PartialEq)]
90 pub struct VersionPart {
91 pub num_a: i32,
92 pub str_b: String,
93 pub num_c: i32,
94 pub extra_d: String,
95 }
96
97 /// Represents a version in the form of a sequence of version parts.
98 ///
99 /// The `Version` struct is used to compare application versions that follow
100 /// a dot-separated format (e.g., `1.0.0`, `98.2pre1.0-beta`). Each part of the version
101 /// is represented by a `VersionPart`.
102 #[derive(Debug, Default, Clone)]
103 pub struct Version(pub Vec<VersionPart>);
104
105 impl PartialEq for Version {
106 fn eq(&self, other: &Self) -> bool {
107 let default_version_part: VersionPart = Default::default();
108 let mut curr_idx = 0;
109 while curr_idx < self.0.len() || curr_idx < other.0.len() {
110 let version_part = self.0.get(curr_idx).unwrap_or(&default_version_part);
111 let other_version_part = other.0.get(curr_idx).unwrap_or(&default_version_part);
112 if !version_part.eq(other_version_part) {
113 return false;
114 }
115 curr_idx += 1
116 }
117 true
118 }
119 }
120
121 impl PartialOrd for Version {
122 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
123 let mut idx = 0;
124 let default_version: VersionPart = Default::default();
125 while idx < self.0.len() || idx < other.0.len() {
126 let version_part = self.0.get(idx).unwrap_or(&default_version);
127 let other_version_part = other.0.get(idx).unwrap_or(&default_version);
128 let ord = version_part.partial_cmp(other_version_part);
129 match ord {
130 Some(Ordering::Greater) | Some(Ordering::Less) => return ord,
131 _ => (),
132 }
133 idx += 1;
134 }
135 Some(Ordering::Equal)
136 }
137 }
138
139 impl PartialOrd for VersionPart {
140 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
141 let num_a_ord = self.num_a.partial_cmp(&other.num_a);
142 match num_a_ord {
143 Some(Ordering::Greater) | Some(Ordering::Less) => return num_a_ord,
144 _ => (),
145 };
146
147 if self.str_b.is_empty() && !other.str_b.is_empty() {
148 return Some(Ordering::Greater);
149 } else if other.str_b.is_empty() && !self.str_b.is_empty() {
150 return Some(Ordering::Less);
151 }
152 let str_b_ord = self.str_b.partial_cmp(&other.str_b);
153 match str_b_ord {
154 Some(Ordering::Greater) | Some(Ordering::Less) => return str_b_ord,
155 _ => (),
156 };
157
158 let num_c_ord = self.num_c.partial_cmp(&other.num_c);
159 match num_c_ord {
160 Some(Ordering::Greater) | Some(Ordering::Less) => return num_c_ord,
161 _ => (),
162 };
163
164 if self.extra_d.is_empty() && !other.extra_d.is_empty() {
165 return Some(Ordering::Greater);
166 } else if other.extra_d.is_empty() && !self.extra_d.is_empty() {
167 return Some(Ordering::Less);
168 }
169 let extra_d_ord = self.extra_d.partial_cmp(&other.extra_d);
170 match extra_d_ord {
171 Some(Ordering::Greater) | Some(Ordering::Less) => return extra_d_ord,
172 _ => (),
173 };
174 Some(Ordering::Equal)
175 }
176 }
177
178 impl TryFrom<&'_ str> for Version {
179 type Error = VersionParsingError;
180 fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
181 let versions = value
182 .split('.')
183 .map(TryInto::try_into)
184 .collect::<Result<Vec<_>, _>>()?;
185 Ok(Version(versions))
186 }
187 }
188
189 impl TryFrom<String> for Version {
190 type Error = VersionParsingError;
191 fn try_from(curr_part: String) -> Result<Self, Self::Error> {
192 curr_part.as_str().try_into()
193 }
194 }
195
196 fn char_at(value: &str, idx: usize) -> Result<char, VersionParsingError> {
197 value.chars().nth(idx).ok_or_else(|| {
198 VersionParsingError::Overflow(format!(
199 "Tried to access character {} in string {}, but it has size {}",
200 idx,
201 value,
202 value.len()
203 ))
204 })
205 }
206
207 fn is_num_c(c: char) -> bool {
208 // TODO: why is the dash here?
209 // this makes `1-beta` end up
210 // having num_a = 1, str_b = "", num_c = 0 and extra_d = "-beta"
211 // is that correct?
212 // Taken from: https://searchfox.org/mozilla-central/rev/77efe87174ee82dad43da56d71a717139b9f19ee/xpcom/base/nsVersionComparator.cpp#107
213 c.is_numeric() || c == '+' || c == '-'
214 }
215
216 fn parse_version_num(val: i32, res: &mut i32) -> Result<(), VersionParsingError> {
217 if *res == 0 {
218 *res = val;
219 } else {
220 let res_l = *res as i64;
221 if (res_l * 10) + val as i64 > i32::MAX as i64 {
222 return Err(VersionParsingError::Overflow(
223 "Number parsing overflows an i32".into(),
224 ));
225 }
226 *res *= 10;
227 *res += val;
228 }
229 Ok(())
230 }
231
232 impl TryFrom<&'_ str> for VersionPart {
233 type Error = VersionParsingError;
234
235 fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
236 if !value.is_ascii() {
237 return Err(VersionParsingError::ParseError(format!(
238 "version string {} contains non-ascii characters",
239 value
240 )));
241 }
242 if value.is_empty() {
243 return Ok(Default::default());
244 }
245
246 let mut res: VersionPart = Default::default();
247 // if the string value is the special "*",
248 // then we set the num_a to be the highest possible value
249 // handle that case before we start
250 if value == "*" {
251 res.num_a = i32::MAX;
252 return Ok(res);
253 }
254 // Step 1: Parse the num_a, it's guaranteed to be
255 // a base-10 number, if it exists
256 let mut curr_idx = 0;
257 while curr_idx < value.len() && char_at(value, curr_idx)?.is_numeric() {
258 parse_version_num(
259 char_at(value, curr_idx)?.to_digit(10).unwrap() as i32,
260 &mut res.num_a,
261 )?;
262 curr_idx += 1;
263 }
264 if curr_idx >= value.len() {
265 return Ok(res);
266 }
267 // Step 2: Parse the str_b. If str_b starts with a "+"
268 // then we increment num_a, and set str_b to be "pre"
269 let first_char = char_at(value, curr_idx)?;
270 if first_char == '+' {
271 res.num_a += 1;
272 res.str_b = "pre".into();
273 return Ok(res);
274 }
275 // otherwise, we parse until we either finish the string
276 // or we find a numeric number, indicating the start of num_c
277 while curr_idx < value.len() && !is_num_c(char_at(value, curr_idx)?) {
278 res.str_b.push(char_at(value, curr_idx)?);
279 curr_idx += 1;
280 }
281
282 if curr_idx >= value.len() {
283 return Ok(res);
284 }
285
286 // Step 3: Parse the num_c, similar to how we parsed num_a
287 while curr_idx < value.len() && char_at(value, curr_idx)?.is_numeric() {
288 parse_version_num(
289 char_at(value, curr_idx)?.to_digit(10).unwrap() as i32,
290 &mut res.num_c,
291 )?;
292 curr_idx += 1;
293 }
294 if curr_idx >= value.len() {
295 return Ok(res);
296 }
297
298 // Step 4: Assign all the remaining to extra_d
299 res.extra_d = value[curr_idx..].into();
300 Ok(res)
301 }
302 }