Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Impl PartialOrd for Version #71

Merged
merged 2 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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());
}
}
Loading