example/
example.rs

1#![allow(clippy::bool_assert_comparison)]
2
3//! Usage examples of the version-compare crate.
4//!
5//! This shows various ways this library provides for comparing version numbers.
6//! The `assert_eq!(...)` macros are used to assert and show the expected output.
7//!
8//! Run this example by invoking `cargo run --example example`.
9
10use version_compare::{compare, compare_to, Cmp, Version};
11
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}