Function compare

Source
pub fn compare<A, B>(a: A, b: B) -> Result<Cmp, ()>
where A: AsRef<str>, B: AsRef<str>,
Expand description

Compare two version number strings to each other.

This compares version a to version b, and returns whether version a is greater, less or equal to version b.

If either version number string is invalid an error is returned.

One of the following operators is returned:

  • Cmp::Eq
  • Cmp::Lt
  • Cmp::Gt

ยงExamples

use version_compare::{Cmp, compare};

assert_eq!(compare("1.2.3", "1.2.3"), Ok(Cmp::Eq));
assert_eq!(compare("1.2.3", "1.2.4"), Ok(Cmp::Lt));
assert_eq!(compare("1", "0.1"), Ok(Cmp::Gt));
Examples found in repository?
examples/minimal.rs (line 13)
9fn main() {
10    let a = "1.3";
11    let b = "1.2.4";
12
13    match compare(a, b) {
14        Ok(Cmp::Lt) => println!("Version a is less than b"),
15        Ok(Cmp::Eq) => println!("Version a is equal to b"),
16        Ok(Cmp::Gt) => println!("Version a is greater than b"),
17        _ => panic!("Invalid version number"),
18    }
19}
More examples
Hide additional examples
examples/example.rs (line 25)
12fn main() {
13    let a = "1.2";
14    let b = "1.5.1";
15
16    // The following comparison operators are used:
17    // - Cmp::Eq -> Equal
18    // - Cmp::Ne -> Not equal
19    // - Cmp::Lt -> Less than
20    // - Cmp::Le -> Less than or equal
21    // - Cmp::Ge -> Greater than or equal
22    // - Cmp::Gt -> Greater than
23
24    // Easily compare version strings
25    assert_eq!(compare(a, b), Ok(Cmp::Lt));
26    assert_eq!(compare_to(a, b, Cmp::Le), Ok(true));
27    assert_eq!(compare_to(a, b, Cmp::Gt), Ok(false));
28
29    // Parse and wrap version strings as a Version
30    let a = Version::from(a).unwrap();
31    let b = Version::from(b).unwrap();
32
33    // The Version can easily be compared with
34    assert_eq!(a < b, true);
35    assert_eq!(a <= b, true);
36    assert_eq!(a > b, false);
37    assert_eq!(a != b, true);
38    assert_eq!(a.compare(&b), Cmp::Lt);
39    assert_eq!(a.compare_to(&b, Cmp::Lt), true);
40
41    // Or match the comparison operators
42    match a.compare(b) {
43        Cmp::Lt => println!("Version a is less than b"),
44        Cmp::Eq => println!("Version a is equal to b"),
45        Cmp::Gt => println!("Version a is greater than b"),
46        _ => unreachable!(),
47    }
48}