rust-lang / rust-lang/libs-team

Introduce a `Compare` trait in the cmp mod

Open
#527 23 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

api-change-proposal
Dominant language
Rust
Stars
178
Forks
28
Avg merge
15m
Merged PRs (30d)
1

Description

Proposal

Problem statement

We have core::cmp::Reverse to wrap a type for changing the ordering logic of a type T. However, under certain generic context, it would introduce unnecessary burden over the input type T where T can be qualified instead.

Introducing a Compare trait can help in such a situation that qualified the type T as is, and accepting a new type C: Compare, acting as a comparator, to switch among different comparison functions.

Motivating examples or use cases

We have functions like:

fn do_register_extremum<T, C>(registry: &mut FuncRegistry, name: &'static str)
where
    T: ConcreteType,
    C: Compare<T::Datum, T::Datum> + Default,
{ ... }

and use the compare traits:

do_register_extremum::<T, Natural<_>>(registry, "min");
do_register_extremum::<T, Rev<Natural<_>>>(registry, "max");

If using core::cmp::Reverse, it would require complex method forwarding to let Reverse<T> implement everything T does.

Take a more complex case, we make a PartialCompare trait based on the Compare trait

/// A trait like [`Compare`] but only requires partial comparison ability.
pub trait PartialCompare<L: ?Sized, R: ?Sized = L> {
    fn compare(&self, l: &L, r: &R) -> Option<Ordering>;

    fn compares_lt(&self, l: &L, r: &R) -> bool {
        matches!(self.compare(l, r), Some(Ordering::Less))
    }

    fn compares_le(&self, l: &L, r: &R) -> bool {
        matches!(
            self.compare(l, r),
            Some(Ordering::Less) | Some(Ordering::Equal)
        )
    }

    fn compares_gt(&self, l: &L, r: &R) -> bool {
        matches!(self.compare(l, r), Some(Ordering::Greater))
    }

    fn compares_ge(&self, l: &L, r: &R) -> bool {
        matches!(
            self.compare(l, r),
            Some(Ordering::Greater) | Some(Ordering::Equal)
        )
    }

    fn compares_eq(&self, l: &L, r: &R) -> bool {
        matches!(self.compare(l, r), Some(Ordering::Equal))
    }

    fn compares_ne(&self, l: &L, r: &R) -> bool {
        !matches!(self.compare(l, r), Some(Ordering::Equal))
    }
}

impl<L, R, C: Compare<L, R>> PartialCompare<L, R> for C {
    fn compare(&self, l: &L, r: &R) -> Option<Ordering> {
        Some(self.compare(l, r))
    }
}

and use it as:

    register_common_comparison::<IntType, IntType, Natural<_>>(registry);
    register_common_comparison::<UIntType, UIntType, Natural<_>>(registry);
    register_common_comparison::<FloatType, FloatType, Natural<_>>(registry);
    register_common_comparison::<BinaryType, BinaryType, Borrowing<Natural<[u8]>, _, _>>(registry);
    register_common_comparison::<StringType, StringType, Borrowing<Natural<str>, _, _>>(registry);
    register_common_comparison::<BooleanType, BooleanType, Natural<_>>(registry);
    register_common_comparison::<TimestampType, TimestampType, Natural<_>>(registry);
    register_common_comparison::<IntervalType, IntervalType, Natural<_>>(registry);
    register_common_comparison::<VariantType, VariantType, VariantCompare>(registry);

    register_common_comparison::<IntType, UIntType, NumericCompare>(registry);
    register_common_comparison::<UIntType, IntType, NumericCompare>(registry);
    register_common_comparison::<IntType, FloatType, NumericCompare>(registry);
    register_common_comparison::<UIntType, FloatType, NumericCompare>(registry);
    register_common_comparison::<FloatType, IntType, NumericCompare>(registry);
    register_common_comparison::<FloatType, UIntType, NumericCompare>(registry);

fn register_common_comparison<T, U, C>(registry: &mut FuncRegistry)
where
    T: ConcreteType,
    U: ConcreteType,
    for<'a> C: PartialCompare<T::DatumRef<'a>, U::DatumRef<'a>> + Default + Copy,
{ .. }

You can imagine if we have to wrap all the types here with Reverse or similar approaches, it would be quite challenging to forward all the traits and make the type system happy.

Solution sketch

Bringing Compare and PartialCompare into the core lib would help in this case, where the compare crate is linked above, and the PartialCompare implementation is inlined above.

I'd first submit this issue to see if this is the way to go, further implement details can go as follow-ups.

Add four traits:

pub trait PartialEqual<L: ?Sized, R: ?Sized = L> {
  fn eq(&self, l: &L, r: &R) -> bool;
  fn ne(&self, l: &L, r: &R) -> bool { .. }
}

pub trait Equal<T: ?Sized>: PartialEqual<T, T> {}

pub trait PartialCompare<L: ?Sized, R: ?Sized = L>: PartialEqual<L, R> {
  fn partial_cmp(&self, l: &L, r: &R) -> Option<Ordering>;
  fn lt(&self, l: &L, r: &R) -> bool { .. }
  fn le(&self, l: &L, r: &R) -> bool { .. }
  fn gt(&self, l: &L, r: &R) -> bool { .. }
  fn ge(&self, l: &L, r: &R) -> bool { .. }
}

pub trait Compare<T: ?Sized>: Equal<T> {
  fn cmp(&self, l: &T, r: &T) -> Ordering;
  fn max(&self, l: T, r: T) -> bool { .. }
  fn min(&self, l: T, r: T) -> bool { .. }
  fn clamp(&self, v: T, l: T, r: T) -> bool { .. }
}

Alternatives

Just use the compare crate or make a new crates.io crate.

However, the compare crate isn't updates for more than nine years, and somehow the core lib has cmp mod that already provides some functionality to support this use case. I wonder if it's suitable as a supplement to the core lib.

Links and related work

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no repository files, tests, or implementation entry points. Start by reading the proposed Compare, PartialCompare, PartialEqual, and Equal APIs alongside the linked compare crate. Done would first require a resolved libs-api review of the problem and proposed standard-library design before implementation work can begin.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.