Skip to content

Simplify PartialOrd on tuples containing primitives #138135

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

Merged
merged 3 commits into from
Mar 24, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
84 changes: 84 additions & 0 deletions library/core/src/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ mod bytewise;
pub(crate) use bytewise::BytewiseEq;

use self::Ordering::*;
use crate::ops::ControlFlow::{self, Break, Continue};

/// Trait for comparisons using the equality operator.
///
Expand Down Expand Up @@ -1446,6 +1447,54 @@ pub macro PartialOrd($item:item) {
/* compiler built-in */
}

/// Helpers for chaining together field PartialOrds into the full type's ordering.
///
/// If the two values are equal, returns `ControlFlow::Continue`.
/// If the two values are not equal, returns `ControlFlow::Break(self OP other)`.
///
/// This allows simple types like `i32` and `f64` to just emit two comparisons
/// directly, instead of needing to optimize the 3-way comparison.
///
/// Currently this is done using specialization, but it doesn't need that:
/// it could be provided methods on `PartialOrd` instead and work fine.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worse for compile times or similar to make these (unstable) provided methods? If we can avoid another use of specialization that seems worthwhile to me - I forget if core's usage is guaranteed sound or not (I seem to recall some gaps)...

Copy link
Member Author

@scottmcm scottmcm Mar 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this usage is sound, since we're only specializing on primitives that don't have lifetimes. But I was torn between the two anyway, so if you have a weak preference for the other way I'm happy to give that a shot. Let's see how it comes out. I always like less specialization 🙂

@rustbot author

pub(crate) trait SpecChainingPartialOrd<Rhs>: PartialOrd<Rhs> {
fn spec_chain_lt(&self, other: &Rhs) -> ControlFlow<bool>;
fn spec_chain_le(&self, other: &Rhs) -> ControlFlow<bool>;
fn spec_chain_gt(&self, other: &Rhs) -> ControlFlow<bool>;
fn spec_chain_ge(&self, other: &Rhs) -> ControlFlow<bool>;
}

impl<T: PartialOrd<U>, U> SpecChainingPartialOrd<U> for T {
#[inline]
default fn spec_chain_lt(&self, other: &U) -> ControlFlow<bool> {
match PartialOrd::partial_cmp(self, other) {
Some(Equal) => Continue(()),
c => Break(c.is_some_and(Ordering::is_lt)),
}
}
#[inline]
default fn spec_chain_le(&self, other: &U) -> ControlFlow<bool> {
match PartialOrd::partial_cmp(self, other) {
Some(Equal) => Continue(()),
c => Break(c.is_some_and(Ordering::is_le)),
}
}
#[inline]
default fn spec_chain_gt(&self, other: &U) -> ControlFlow<bool> {
match PartialOrd::partial_cmp(self, other) {
Some(Equal) => Continue(()),
c => Break(c.is_some_and(Ordering::is_gt)),
}
}
#[inline]
default fn spec_chain_ge(&self, other: &U) -> ControlFlow<bool> {
match PartialOrd::partial_cmp(self, other) {
Some(Equal) => Continue(()),
c => Break(c.is_some_and(Ordering::is_ge)),
}
}
}

/// Compares and returns the minimum of two values.
///
/// Returns the first argument if the comparison determines them to be equal.
Expand Down Expand Up @@ -1741,6 +1790,7 @@ where
mod impls {
use crate::cmp::Ordering::{self, Equal, Greater, Less};
use crate::hint::unreachable_unchecked;
use crate::ops::ControlFlow::{self, Break, Continue};

macro_rules! partial_eq_impl {
($($t:ty)*) => ($(
Expand Down Expand Up @@ -1779,6 +1829,36 @@ mod impls {

eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }

macro_rules! chaining_impl {
($t:ty) => {
// These implementations are the same for `Ord` or `PartialOrd` types
// because if either is NAN the `==` test will fail so we end up in
// the `Break` case and the comparison will correctly return `false`.
impl super::SpecChainingPartialOrd<$t> for $t {
#[inline]
fn spec_chain_lt(&self, other: &Self) -> ControlFlow<bool> {
let (lhs, rhs) = (*self, *other);
if lhs == rhs { Continue(()) } else { Break(lhs < rhs) }
}
#[inline]
fn spec_chain_le(&self, other: &Self) -> ControlFlow<bool> {
let (lhs, rhs) = (*self, *other);
if lhs == rhs { Continue(()) } else { Break(lhs <= rhs) }
}
#[inline]
fn spec_chain_gt(&self, other: &Self) -> ControlFlow<bool> {
let (lhs, rhs) = (*self, *other);
if lhs == rhs { Continue(()) } else { Break(lhs > rhs) }
}
#[inline]
fn spec_chain_ge(&self, other: &Self) -> ControlFlow<bool> {
let (lhs, rhs) = (*self, *other);
if lhs == rhs { Continue(()) } else { Break(lhs >= rhs) }
}
}
};
}

macro_rules! partial_ord_impl {
($($t:ty)*) => ($(
#[stable(feature = "rust1", since = "1.0.0")]
Expand All @@ -1801,6 +1881,8 @@ mod impls {
#[inline(always)]
fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
}

chaining_impl!($t);
)*)
}

Expand Down Expand Up @@ -1840,6 +1922,8 @@ mod impls {
fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
}

chaining_impl!($t);

#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for $t {
#[inline]
Expand Down
25 changes: 14 additions & 11 deletions library/core/src/tuple.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// See core/src/primitive_docs.rs for documentation.

use crate::cmp::Ordering::{self, *};
use crate::cmp::SpecChainingPartialOrd;
use crate::marker::{ConstParamTy_, StructuralPartialEq, UnsizedConstParamTy};
use crate::ops::ControlFlow::{Break, Continue};

// Recursive macro for implementing n-ary tuple functions and operations
//
Expand Down Expand Up @@ -80,19 +82,19 @@ macro_rules! tuple_impls {
}
#[inline]
fn lt(&self, other: &($($T,)+)) -> bool {
lexical_ord!(lt, Less, $( ${ignore($T)} self.${index()}, other.${index()} ),+)
lexical_ord!(lt, spec_chain_lt, $( ${ignore($T)} self.${index()}, other.${index()} ),+)
}
#[inline]
fn le(&self, other: &($($T,)+)) -> bool {
lexical_ord!(le, Less, $( ${ignore($T)} self.${index()}, other.${index()} ),+)
lexical_ord!(le, spec_chain_le, $( ${ignore($T)} self.${index()}, other.${index()} ),+)
}
#[inline]
fn ge(&self, other: &($($T,)+)) -> bool {
lexical_ord!(ge, Greater, $( ${ignore($T)} self.${index()}, other.${index()} ),+)
lexical_ord!(ge, spec_chain_ge, $( ${ignore($T)} self.${index()}, other.${index()} ),+)
}
#[inline]
fn gt(&self, other: &($($T,)+)) -> bool {
lexical_ord!(gt, Greater, $( ${ignore($T)} self.${index()}, other.${index()} ),+)
lexical_ord!(gt, spec_chain_gt, $( ${ignore($T)} self.${index()}, other.${index()} ),+)
}
}
}
Expand Down Expand Up @@ -171,15 +173,16 @@ macro_rules! maybe_tuple_doc {
// `(a1, a2, a3) < (b1, b2, b3)` would be `lexical_ord!(lt, opt_is_lt, a1, b1,
// a2, b2, a3, b3)` (and similarly for `lexical_cmp`)
//
// `$ne_rel` is only used to determine the result after checking that they're
// not equal, so `lt` and `le` can both just use `Less`.
// `$chain_rel` is the method from `SpecChainingPartialOrd` to use for all but the
// final value, to produce better results for simple primitives.
macro_rules! lexical_ord {
($rel: ident, $ne_rel: ident, $a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {{
let c = PartialOrd::partial_cmp(&$a, &$b);
if c != Some(Equal) { c == Some($ne_rel) }
else { lexical_ord!($rel, $ne_rel, $($rest_a, $rest_b),+) }
($rel: ident, $chain_rel: ident, $a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {{
match SpecChainingPartialOrd::$chain_rel(&$a, &$b) {
Break(val) => val,
Continue(()) => lexical_ord!($rel, $chain_rel, $($rest_a, $rest_b),+),
}
}};
($rel: ident, $ne_rel: ident, $a:expr, $b:expr) => {
($rel: ident, $chain_rel: ident, $a:expr, $b:expr) => {
// Use the specific method for the last element
PartialOrd::$rel(&$a, &$b)
};
Expand Down
Loading
Loading