Skip to content

Commit 83aaaf0

Browse files
committed
Add a method for precedence comparison of Versions
1 parent 83154ea commit 83aaaf0

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/lib.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ mod serde;
102102

103103
use crate::alloc::vec::Vec;
104104
use crate::identifier::Identifier;
105+
use core::cmp::Ordering;
105106
use core::str::FromStr;
106107

107108
#[allow(unused_imports)]
@@ -431,6 +432,53 @@ impl Version {
431432
pub fn parse(text: &str) -> Result<Self, Error> {
432433
Version::from_str(text)
433434
}
435+
436+
/// Compare the major, minor, patch, and pre-release value of two versions,
437+
/// disregarding build metadata. Versions that differ only in build metadata
438+
/// are considered equal. This comparison is what the SemVer spec refers to
439+
/// as "precedence".
440+
///
441+
/// # Example
442+
///
443+
/// ```
444+
/// use semver::Version;
445+
///
446+
/// let mut versions = [
447+
/// "1.20.0+c144a98".parse::<Version>().unwrap(),
448+
/// "1.20.0".parse().unwrap(),
449+
/// "1.0.0".parse().unwrap(),
450+
/// "1.0.0-alpha".parse().unwrap(),
451+
/// "1.20.0+bc17664".parse().unwrap(),
452+
/// ];
453+
///
454+
/// // This is a stable sort, so it preserves the relative order of equal
455+
/// // elements. The three 1.20.0 versions differ only in build metadata so
456+
/// // they are not reordered relative to one another.
457+
/// versions.sort_by(Version::cmp_precedence);
458+
/// assert_eq!(versions, [
459+
/// "1.0.0-alpha".parse().unwrap(),
460+
/// "1.0.0".parse().unwrap(),
461+
/// "1.20.0+c144a98".parse().unwrap(),
462+
/// "1.20.0".parse().unwrap(),
463+
/// "1.20.0+bc17664".parse().unwrap(),
464+
/// ]);
465+
///
466+
/// // Totally order the versions, including comparing the build metadata.
467+
/// versions.sort();
468+
/// assert_eq!(versions, [
469+
/// "1.0.0-alpha".parse().unwrap(),
470+
/// "1.0.0".parse().unwrap(),
471+
/// "1.20.0".parse().unwrap(),
472+
/// "1.20.0+bc17664".parse().unwrap(),
473+
/// "1.20.0+c144a98".parse().unwrap(),
474+
/// ]);
475+
/// ```
476+
pub fn cmp_precedence(&self, other: &Self) -> Ordering {
477+
Ord::cmp(
478+
&(self.major, self.minor, self.patch, &self.pre),
479+
&(other.major, other.minor, other.patch, &other.pre),
480+
)
481+
}
434482
}
435483

436484
impl VersionReq {

0 commit comments

Comments
 (0)