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

Add a method for precedence comparison of Versions #305

Merged
merged 1 commit into from
Oct 9, 2023
Merged
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
48 changes: 48 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ mod serde;

use crate::alloc::vec::Vec;
use crate::identifier::Identifier;
use core::cmp::Ordering;
use core::str::FromStr;

#[allow(unused_imports)]
Expand Down Expand Up @@ -431,6 +432,53 @@ impl Version {
pub fn parse(text: &str) -> Result<Self, Error> {
Version::from_str(text)
}

/// Compare the major, minor, patch, and pre-release value of two versions,
/// disregarding build metadata. Versions that differ only in build metadata
/// are considered equal. This comparison is what the SemVer spec refers to
/// as "precedence".
///
/// # Example
///
/// ```
/// use semver::Version;
///
/// let mut versions = [
/// "1.20.0+c144a98".parse::<Version>().unwrap(),
/// "1.20.0".parse().unwrap(),
/// "1.0.0".parse().unwrap(),
/// "1.0.0-alpha".parse().unwrap(),
/// "1.20.0+bc17664".parse().unwrap(),
/// ];
///
/// // This is a stable sort, so it preserves the relative order of equal
/// // elements. The three 1.20.0 versions differ only in build metadata so
/// // they are not reordered relative to one another.
/// versions.sort_by(Version::cmp_precedence);
/// assert_eq!(versions, [
/// "1.0.0-alpha".parse().unwrap(),
/// "1.0.0".parse().unwrap(),
/// "1.20.0+c144a98".parse().unwrap(),
/// "1.20.0".parse().unwrap(),
/// "1.20.0+bc17664".parse().unwrap(),
/// ]);
///
/// // Totally order the versions, including comparing the build metadata.
/// versions.sort();
/// assert_eq!(versions, [
/// "1.0.0-alpha".parse().unwrap(),
/// "1.0.0".parse().unwrap(),
/// "1.20.0".parse().unwrap(),
/// "1.20.0+bc17664".parse().unwrap(),
/// "1.20.0+c144a98".parse().unwrap(),
/// ]);
/// ```
pub fn cmp_precedence(&self, other: &Self) -> Ordering {
Ord::cmp(
&(self.major, self.minor, self.patch, &self.pre),
&(other.major, other.minor, other.patch, &other.pre),
)
}
}

impl VersionReq {
Expand Down