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

Compare two version number strings to each other and test against the given comparison operator.

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

§Examples

use version_compare::{Cmp, compare_to};

assert!(compare_to("1.2.3", "1.2.3", Cmp::Eq).unwrap());
assert!(compare_to("1.2.3", "1.2.3", Cmp::Le).unwrap());
assert!(compare_to("1.2.3", "1.2.4", Cmp::Lt).unwrap());
assert!(compare_to("1", "0.1", Cmp::Gt).unwrap());
assert!(compare_to("1", "0.1", Cmp::Ge).unwrap());
Examples found in repository?
examples/example.rs (line 26)
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!(),
    }
}