Skip to content

Commit

Permalink
Merge pull request #71 from wizardsardine/partialord-version
Browse files Browse the repository at this point in the history
Impl PartialOrd for Version
  • Loading branch information
edouardparis authored Feb 23, 2024
2 parents 49aa70a + 1f491be commit 51aea7c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ keywords = ["bitcoin"]

[package]
name = "async-hwi"
version = "0.0.14"
version = "0.0.15"
readme = "README.md"
description = "Async hardware wallet interface"
license-file.workspace = true
Expand Down
49 changes: 48 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use bitcoin::{
psbt::Psbt,
};

use std::{fmt::Debug, str::FromStr};
use std::{cmp::Ordering, fmt::Debug, str::FromStr};

#[derive(Debug, Clone)]
pub enum Error {
Expand Down Expand Up @@ -128,6 +128,29 @@ pub fn parse_version(s: &str) -> Result<Version, Error> {
}
}

impl PartialOrd for Version {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.major.cmp(&other.major) {
Ordering::Equal => match self.minor.cmp(&other.minor) {
Ordering::Equal => match self.patch.cmp(&other.patch) {
Ordering::Equal => {
match (&self.prerelease, &other.prerelease) {
// Cannot compare versions at this point.
(Some(_), Some(_)) => None,
(Some(_), None) => Some(Ordering::Greater),
(None, Some(_)) => Some(Ordering::Less),
(None, None) => Some(Ordering::Equal),
}
}
other => Some(other),
},
other => Some(other),
},
other => Some(other),
}
}
}

impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(prerelease) = &self.prerelease {
Expand Down Expand Up @@ -240,4 +263,28 @@ mod tests {
assert_eq!(v, parse_version(s).unwrap());
}
}

#[cfg(feature = "regex")]
#[test]
fn test_partial_ord_version() {
let test_cases = [
("v2.1.0", "v3.1.0"),
("v0.0.1", "v0.1"),
("v0.1", "v1.0.1"),
("v2.0.1", "v2.1.0"),
("v2.1.1", "v3.0-rc1"),
("v3.0-rc1", "v3.0.1"),
("v3.0", "v3.0-rc1"),
];
for (l, r) in test_cases {
let v1 = parse_version(l).unwrap();
let v2 = parse_version(r).unwrap();
assert!(v1 < v2);
}

// We cannot compare prerelease of the same version.
let v1 = parse_version("v2.0-rc1weirdstuff").unwrap();
let v2 = parse_version("v2.0-rc1weirderstuff").unwrap();
assert!(v1.partial_cmp(&v2).is_none());
}
}

0 comments on commit 51aea7c

Please sign in to comment.