Function compare_to

Source
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)
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}