Function version_compare::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)
9
10
11
12
13
14
15
16
17
18
19
fn main() {
    let a = "1.3";
    let b = "1.2.4";

    match compare(a, b) {
        Ok(Cmp::Lt) => println!("Version a is less than b"),
        Ok(Cmp::Eq) => println!("Version a is equal to b"),
        Ok(Cmp::Gt) => println!("Version a is greater than b"),
        _ => panic!("Invalid version number"),
    }
}
More examples
Hide additional examples
examples/example.rs (line 25)
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let a = "1.2";
    let b = "1.5.1";

    // The following comparison operators are used:
    // - Cmp::Eq -> Equal
    // - Cmp::Ne -> Not equal
    // - Cmp::Lt -> Less than
    // - Cmp::Le -> Less than or equal
    // - Cmp::Ge -> Greater than or equal
    // - Cmp::Gt -> Greater than

    // Easily compare version strings
    assert_eq!(compare(a, b), Ok(Cmp::Lt));
    assert_eq!(compare_to(a, b, Cmp::Le), Ok(true));
    assert_eq!(compare_to(a, b, Cmp::Gt), Ok(false));

    // Parse and wrap version strings as a Version
    let a = Version::from(a).unwrap();
    let b = Version::from(b).unwrap();

    // The Version can easily be compared with
    assert_eq!(a < b, true);
    assert_eq!(a <= b, true);
    assert_eq!(a > b, false);
    assert_eq!(a != b, true);
    assert_eq!(a.compare(&b), Cmp::Lt);
    assert_eq!(a.compare_to(&b, Cmp::Lt), true);

    // Or match the comparison operators
    match a.compare(b) {
        Cmp::Lt => println!("Version a is less than b"),
        Cmp::Eq => println!("Version a is equal to b"),
        Cmp::Gt => println!("Version a is greater than b"),
        _ => unreachable!(),
    }
}