1 //! Functionality for ordering and comparison.
3 //! This module contains various tools for ordering and comparing values. In
6 //! * [`Eq`] and [`PartialEq`] are traits that allow you to define total and
7 //! partial equality between values, respectively. Implementing them overloads
8 //! the `==` and `!=` operators.
9 //! * [`Ord`] and [`PartialOrd`] are traits that allow you to define total and
10 //! partial orderings between values, respectively. Implementing them overloads
11 //! the `<`, `<=`, `>`, and `>=` operators.
12 //! * [`Ordering`] is an enum returned by the main functions of [`Ord`] and
13 //! [`PartialOrd`], and describes an ordering.
14 //! * [`Reverse`] is a struct that allows you to easily reverse an ordering.
15 //! * [`max`] and [`min`] are functions that build off of [`Ord`] and allow you
16 //! to find the maximum or minimum of two values.
18 //! For more details, see the respective documentation of each item in the list.
23 #![stable(feature = "rust1", since = "1.0.0")]
25 use self::Ordering
::*;
27 /// Trait for equality comparisons which are [partial equivalence
28 /// relations](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
30 /// This trait allows for partial equality, for types that do not have a full
31 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
32 /// so floating point types implement `PartialEq` but not [`Eq`](Eq).
34 /// Formally, the equality must be (for all `a`, `b` and `c`):
36 /// - symmetric: `a == b` implies `b == a`; and
37 /// - transitive: `a == b` and `b == c` implies `a == c`.
39 /// Note that these requirements mean that the trait itself must be implemented
40 /// symmetrically and transitively: if `T: PartialEq<U>` and `U: PartialEq<V>`
41 /// then `U: PartialEq<T>` and `T: PartialEq<V>`.
45 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
46 /// instances are equal if all fields are equal, and not equal if any fields
47 /// are not equal. When `derive`d on enums, each variant is equal to itself
48 /// and not equal to the other variants.
50 /// ## How can I implement `PartialEq`?
52 /// `PartialEq` only requires the [`eq`] method to be implemented; [`ne`] is defined
53 /// in terms of it by default. Any manual implementation of [`ne`] *must* respect
54 /// the rule that [`eq`] is a strict inverse of [`ne`]; that is, `!(a == b)` if and
57 /// Implementations of `PartialEq`, [`PartialOrd`], and [`Ord`] *must* agree with
58 /// each other. It's easy to accidentally make them disagree by deriving some
59 /// of the traits and manually implementing others.
61 /// An example implementation for a domain in which two books are considered
62 /// the same book if their ISBN matches, even if the formats differ:
73 /// format: BookFormat,
76 /// impl PartialEq for Book {
77 /// fn eq(&self, other: &Self) -> bool {
78 /// self.isbn == other.isbn
82 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
83 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
84 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
86 /// assert!(b1 == b2);
87 /// assert!(b1 != b3);
90 /// ## How can I compare two different types?
92 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
93 /// For example, let's tweak our previous code a bit:
96 /// // The derive implements <BookFormat> == <BookFormat> comparisons
97 /// #[derive(PartialEq)]
106 /// format: BookFormat,
109 /// // Implement <Book> == <BookFormat> comparisons
110 /// impl PartialEq<BookFormat> for Book {
111 /// fn eq(&self, other: &BookFormat) -> bool {
112 /// self.format == *other
116 /// // Implement <BookFormat> == <Book> comparisons
117 /// impl PartialEq<Book> for BookFormat {
118 /// fn eq(&self, other: &Book) -> bool {
119 /// *self == other.format
123 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
125 /// assert!(b1 == BookFormat::Paperback);
126 /// assert!(BookFormat::Ebook != b1);
129 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
130 /// we allow `BookFormat`s to be compared with `Book`s.
132 /// A comparison like the one above, which ignores some fields of the struct,
133 /// can be dangerous. It can easily lead to an unintended violation of the
134 /// requirements for a partial equivalence relation. For example, if we kept
135 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
136 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
137 /// via the manual implementation from the first example) then the result would
138 /// violate transitivity:
141 /// #[derive(PartialEq)]
142 /// enum BookFormat {
148 /// #[derive(PartialEq)]
151 /// format: BookFormat,
154 /// impl PartialEq<BookFormat> for Book {
155 /// fn eq(&self, other: &BookFormat) -> bool {
156 /// self.format == *other
160 /// impl PartialEq<Book> for BookFormat {
161 /// fn eq(&self, other: &Book) -> bool {
162 /// *self == other.format
167 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
168 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
170 /// assert!(b1 == BookFormat::Paperback);
171 /// assert!(BookFormat::Paperback == b2);
173 /// // The following should hold by transitivity but doesn't.
174 /// assert!(b1 == b2); // <-- PANICS
184 /// assert_eq!(x == y, false);
185 /// assert_eq!(x.eq(&y), false);
188 /// [`eq`]: PartialEq::eq
189 /// [`ne`]: PartialEq::ne
191 #[stable(feature = "rust1", since = "1.0.0")]
194 #[rustc_on_unimplemented(
195 message
= "can't compare `{Self}` with `{Rhs}`",
196 label
= "no implementation for `{Self} == {Rhs}`"
198 pub trait PartialEq
<Rhs
: ?Sized
= Self> {
199 /// This method tests for `self` and `other` values to be equal, and is used
202 #[stable(feature = "rust1", since = "1.0.0")]
203 fn eq(&self, other
: &Rhs
) -> bool
;
205 /// This method tests for `!=`.
208 #[stable(feature = "rust1", since = "1.0.0")]
209 fn ne(&self, other
: &Rhs
) -> bool
{
214 /// Derive macro generating an impl of the trait `PartialEq`.
215 #[rustc_builtin_macro]
216 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
217 #[allow_internal_unstable(core_intrinsics, structural_match)]
218 pub macro PartialEq($item
:item
) {
219 /* compiler built-in */
222 /// Trait for equality comparisons which are [equivalence relations](
223 /// https://en.wikipedia.org/wiki/Equivalence_relation).
225 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
226 /// be (for all `a`, `b` and `c`):
228 /// - reflexive: `a == a`;
229 /// - symmetric: `a == b` implies `b == a`; and
230 /// - transitive: `a == b` and `b == c` implies `a == c`.
232 /// This property cannot be checked by the compiler, and therefore `Eq` implies
233 /// [`PartialEq`], and has no extra methods.
237 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
238 /// no extra methods, it is only informing the compiler that this is an
239 /// equivalence relation rather than a partial equivalence relation. Note that
240 /// the `derive` strategy requires all fields are `Eq`, which isn't
243 /// ## How can I implement `Eq`?
245 /// If you cannot use the `derive` strategy, specify that your type implements
246 /// `Eq`, which has no methods:
249 /// enum BookFormat { Paperback, Hardback, Ebook }
252 /// format: BookFormat,
254 /// impl PartialEq for Book {
255 /// fn eq(&self, other: &Self) -> bool {
256 /// self.isbn == other.isbn
259 /// impl Eq for Book {}
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub trait Eq
: PartialEq
<Self> {
265 // this method is used solely by #[deriving] to assert
266 // that every component of a type implements #[deriving]
267 // itself, the current deriving infrastructure means doing this
268 // assertion without using a method on this trait is nearly
271 // This should never be implemented by hand.
274 #[stable(feature = "rust1", since = "1.0.0")]
275 fn assert_receiver_is_total_eq(&self) {}
278 /// Derive macro generating an impl of the trait `Eq`.
279 #[rustc_builtin_macro]
280 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
281 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match)]
282 pub macro Eq($item
:item
) {
283 /* compiler built-in */
286 // FIXME: this struct is used solely by #[derive] to
287 // assert that every component of a type implements Eq.
289 // This struct should never appear in user code.
291 #[allow(missing_debug_implementations)]
292 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
293 pub struct AssertParamIsEq
<T
: Eq
+ ?Sized
> {
294 _field
: crate::marker
::PhantomData
<T
>,
297 /// An `Ordering` is the result of a comparison between two values.
302 /// use std::cmp::Ordering;
304 /// let result = 1.cmp(&2);
305 /// assert_eq!(Ordering::Less, result);
307 /// let result = 1.cmp(&1);
308 /// assert_eq!(Ordering::Equal, result);
310 /// let result = 2.cmp(&1);
311 /// assert_eq!(Ordering::Greater, result);
313 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
314 #[stable(feature = "rust1", since = "1.0.0")]
316 /// An ordering where a compared value is less than another.
317 #[stable(feature = "rust1", since = "1.0.0")]
319 /// An ordering where a compared value is equal to another.
320 #[stable(feature = "rust1", since = "1.0.0")]
322 /// An ordering where a compared value is greater than another.
323 #[stable(feature = "rust1", since = "1.0.0")]
328 /// Reverses the `Ordering`.
330 /// * `Less` becomes `Greater`.
331 /// * `Greater` becomes `Less`.
332 /// * `Equal` becomes `Equal`.
339 /// use std::cmp::Ordering;
341 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
342 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
343 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
346 /// This method can be used to reverse a comparison:
349 /// let data: &mut [_] = &mut [2, 10, 5, 8];
351 /// // sort the array from largest to smallest.
352 /// data.sort_by(|a, b| a.cmp(b).reverse());
354 /// let b: &mut [_] = &mut [10, 8, 5, 2];
355 /// assert!(data == b);
359 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub const fn reverse(self) -> Ordering
{
369 /// Chains two orderings.
371 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
376 /// use std::cmp::Ordering;
378 /// let result = Ordering::Equal.then(Ordering::Less);
379 /// assert_eq!(result, Ordering::Less);
381 /// let result = Ordering::Less.then(Ordering::Equal);
382 /// assert_eq!(result, Ordering::Less);
384 /// let result = Ordering::Less.then(Ordering::Greater);
385 /// assert_eq!(result, Ordering::Less);
387 /// let result = Ordering::Equal.then(Ordering::Equal);
388 /// assert_eq!(result, Ordering::Equal);
390 /// let x: (i64, i64, i64) = (1, 2, 7);
391 /// let y: (i64, i64, i64) = (1, 5, 3);
392 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
394 /// assert_eq!(result, Ordering::Less);
398 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
399 #[stable(feature = "ordering_chaining", since = "1.17.0")]
400 pub const fn then(self, other
: Ordering
) -> Ordering
{
407 /// Chains the ordering with the given function.
409 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
415 /// use std::cmp::Ordering;
417 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
418 /// assert_eq!(result, Ordering::Less);
420 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
421 /// assert_eq!(result, Ordering::Less);
423 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
424 /// assert_eq!(result, Ordering::Less);
426 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
427 /// assert_eq!(result, Ordering::Equal);
429 /// let x: (i64, i64, i64) = (1, 2, 7);
430 /// let y: (i64, i64, i64) = (1, 5, 3);
431 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
433 /// assert_eq!(result, Ordering::Less);
437 #[stable(feature = "ordering_chaining", since = "1.17.0")]
438 pub fn then_with
<F
: FnOnce() -> Ordering
>(self, f
: F
) -> Ordering
{
446 /// A helper struct for reverse ordering.
448 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
449 /// can be used to reverse order a part of a key.
451 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
456 /// use std::cmp::Reverse;
458 /// let mut v = vec![1, 2, 3, 4, 5, 6];
459 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
460 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
462 #[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
463 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
464 pub struct Reverse
<T
>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
466 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
467 impl<T
: PartialOrd
> PartialOrd
for Reverse
<T
> {
469 fn partial_cmp(&self, other
: &Reverse
<T
>) -> Option
<Ordering
> {
470 other
.0.partial_cmp(&self.0)
474 fn lt(&self, other
: &Self) -> bool
{
478 fn le(&self, other
: &Self) -> bool
{
482 fn gt(&self, other
: &Self) -> bool
{
486 fn ge(&self, other
: &Self) -> bool
{
491 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
492 impl<T
: Ord
> Ord
for Reverse
<T
> {
494 fn cmp(&self, other
: &Reverse
<T
>) -> Ordering
{
499 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
501 /// An order is a total order if it is (for all `a`, `b` and `c`):
503 /// - total and asymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
504 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
508 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
509 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
510 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
512 /// ## How can I implement `Ord`?
514 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
516 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
517 /// [`cmp`] on your type's fields.
519 /// Implementations of [`PartialEq`], [`PartialOrd`], and `Ord` *must*
520 /// agree with each other. That is, `a.cmp(b) == Ordering::Equal` if
521 /// and only if `a == b` and `Some(a.cmp(b)) == a.partial_cmp(b)` for
522 /// all `a` and `b`. It's easy to accidentally make them disagree by
523 /// deriving some of the traits and manually implementing others.
525 /// Here's an example where you want to sort people by height only, disregarding `id`
529 /// use std::cmp::Ordering;
538 /// impl Ord for Person {
539 /// fn cmp(&self, other: &Self) -> Ordering {
540 /// self.height.cmp(&other.height)
544 /// impl PartialOrd for Person {
545 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
546 /// Some(self.cmp(other))
550 /// impl PartialEq for Person {
551 /// fn eq(&self, other: &Self) -> bool {
552 /// self.height == other.height
557 /// [`cmp`]: Ord::cmp
562 #[stable(feature = "rust1", since = "1.0.0")]
563 pub trait Ord
: Eq
+ PartialOrd
<Self> {
564 /// This method returns an [`Ordering`] between `self` and `other`.
566 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
567 /// `self <operator> other` if true.
572 /// use std::cmp::Ordering;
574 /// assert_eq!(5.cmp(&10), Ordering::Less);
575 /// assert_eq!(10.cmp(&5), Ordering::Greater);
576 /// assert_eq!(5.cmp(&5), Ordering::Equal);
579 #[stable(feature = "rust1", since = "1.0.0")]
580 fn cmp(&self, other
: &Self) -> Ordering
;
582 /// Compares and returns the maximum of two values.
584 /// Returns the second argument if the comparison determines them to be equal.
589 /// assert_eq!(2, 1.max(2));
590 /// assert_eq!(2, 2.max(2));
592 #[stable(feature = "ord_max_min", since = "1.21.0")]
595 fn max(self, other
: Self) -> Self
599 max_by(self, other
, Ord
::cmp
)
602 /// Compares and returns the minimum of two values.
604 /// Returns the first argument if the comparison determines them to be equal.
609 /// assert_eq!(1, 1.min(2));
610 /// assert_eq!(2, 2.min(2));
612 #[stable(feature = "ord_max_min", since = "1.21.0")]
615 fn min(self, other
: Self) -> Self
619 min_by(self, other
, Ord
::cmp
)
622 /// Restrict a value to a certain interval.
624 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
625 /// less than `min`. Otherwise this returns `self`.
629 /// Panics if `min > max`.
634 /// #![feature(clamp)]
636 /// assert!((-3).clamp(-2, 1) == -2);
637 /// assert!(0.clamp(-2, 1) == 0);
638 /// assert!(2.clamp(-2, 1) == 1);
641 #[unstable(feature = "clamp", issue = "44095")]
642 fn clamp(self, min
: Self, max
: Self) -> Self
649 } else if self > max
{
657 /// Derive macro generating an impl of the trait `Ord`.
658 #[rustc_builtin_macro]
659 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
660 #[allow_internal_unstable(core_intrinsics)]
661 pub macro Ord($item
:item
) {
662 /* compiler built-in */
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl Eq
for Ordering {}
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl Ord
for Ordering
{
671 fn cmp(&self, other
: &Ordering
) -> Ordering
{
672 (*self as i32).cmp(&(*other
as i32))
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl PartialOrd
for Ordering
{
679 fn partial_cmp(&self, other
: &Ordering
) -> Option
<Ordering
> {
680 (*self as i32).partial_cmp(&(*other
as i32))
684 /// Trait for values that can be compared for a sort-order.
686 /// The comparison must satisfy, for all `a`, `b` and `c`:
688 /// - asymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
689 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
691 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
692 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
697 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
698 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
699 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
701 /// ## How can I implement `PartialOrd`?
703 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
704 /// generated from default implementations.
706 /// However it remains possible to implement the others separately for types which do not have a
707 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
708 /// false` (cf. IEEE 754-2008 section 5.11).
710 /// `PartialOrd` requires your type to be [`PartialEq`].
712 /// Implementations of [`PartialEq`], `PartialOrd`, and [`Ord`] *must* agree with each other. It's
713 /// easy to accidentally make them disagree by deriving some of the traits and manually
714 /// implementing others.
716 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
719 /// use std::cmp::Ordering;
728 /// impl PartialOrd for Person {
729 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
730 /// Some(self.cmp(other))
734 /// impl Ord for Person {
735 /// fn cmp(&self, other: &Self) -> Ordering {
736 /// self.height.cmp(&other.height)
740 /// impl PartialEq for Person {
741 /// fn eq(&self, other: &Self) -> bool {
742 /// self.height == other.height
747 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
748 /// is an example of `Person` types who have a floating-point `height` field that
749 /// is the only field to be used for sorting:
752 /// use std::cmp::Ordering;
760 /// impl PartialOrd for Person {
761 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
762 /// self.height.partial_cmp(&other.height)
766 /// impl PartialEq for Person {
767 /// fn eq(&self, other: &Self) -> bool {
768 /// self.height == other.height
779 /// assert_eq!(x < y, true);
780 /// assert_eq!(x.lt(&y), true);
783 /// [`partial_cmp`]: PartialOrd::partial_cmp
784 /// [`cmp`]: Ord::cmp
785 #[lang = "partial_ord"]
786 #[stable(feature = "rust1", since = "1.0.0")]
791 #[rustc_on_unimplemented(
792 message
= "can't compare `{Self}` with `{Rhs}`",
793 label
= "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
795 pub trait PartialOrd
<Rhs
: ?Sized
= Self>: PartialEq
<Rhs
> {
796 /// This method returns an ordering between `self` and `other` values if one exists.
801 /// use std::cmp::Ordering;
803 /// let result = 1.0.partial_cmp(&2.0);
804 /// assert_eq!(result, Some(Ordering::Less));
806 /// let result = 1.0.partial_cmp(&1.0);
807 /// assert_eq!(result, Some(Ordering::Equal));
809 /// let result = 2.0.partial_cmp(&1.0);
810 /// assert_eq!(result, Some(Ordering::Greater));
813 /// When comparison is impossible:
816 /// let result = f64::NAN.partial_cmp(&1.0);
817 /// assert_eq!(result, None);
820 #[stable(feature = "rust1", since = "1.0.0")]
821 fn partial_cmp(&self, other
: &Rhs
) -> Option
<Ordering
>;
823 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
828 /// let result = 1.0 < 2.0;
829 /// assert_eq!(result, true);
831 /// let result = 2.0 < 1.0;
832 /// assert_eq!(result, false);
836 #[stable(feature = "rust1", since = "1.0.0")]
837 fn lt(&self, other
: &Rhs
) -> bool
{
838 matches
!(self.partial_cmp(other
), Some(Less
))
841 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
847 /// let result = 1.0 <= 2.0;
848 /// assert_eq!(result, true);
850 /// let result = 2.0 <= 2.0;
851 /// assert_eq!(result, true);
855 #[stable(feature = "rust1", since = "1.0.0")]
856 fn le(&self, other
: &Rhs
) -> bool
{
857 matches
!(self.partial_cmp(other
), Some(Less
| Equal
))
860 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
865 /// let result = 1.0 > 2.0;
866 /// assert_eq!(result, false);
868 /// let result = 2.0 > 2.0;
869 /// assert_eq!(result, false);
873 #[stable(feature = "rust1", since = "1.0.0")]
874 fn gt(&self, other
: &Rhs
) -> bool
{
875 matches
!(self.partial_cmp(other
), Some(Greater
))
878 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
884 /// let result = 2.0 >= 1.0;
885 /// assert_eq!(result, true);
887 /// let result = 2.0 >= 2.0;
888 /// assert_eq!(result, true);
892 #[stable(feature = "rust1", since = "1.0.0")]
893 fn ge(&self, other
: &Rhs
) -> bool
{
894 matches
!(self.partial_cmp(other
), Some(Greater
| Equal
))
898 /// Derive macro generating an impl of the trait `PartialOrd`.
899 #[rustc_builtin_macro]
900 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
901 #[allow_internal_unstable(core_intrinsics)]
902 pub macro PartialOrd($item
:item
) {
903 /* compiler built-in */
906 /// Compares and returns the minimum of two values.
908 /// Returns the first argument if the comparison determines them to be equal.
910 /// Internally uses an alias to [`Ord::min`].
917 /// assert_eq!(1, cmp::min(1, 2));
918 /// assert_eq!(2, cmp::min(2, 2));
922 #[stable(feature = "rust1", since = "1.0.0")]
923 pub fn min
<T
: Ord
>(v1
: T
, v2
: T
) -> T
{
927 /// Returns the minimum of two values with respect to the specified comparison function.
929 /// Returns the first argument if the comparison determines them to be equal.
934 /// #![feature(cmp_min_max_by)]
938 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
939 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
943 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
944 pub fn min_by
<T
, F
: FnOnce(&T
, &T
) -> Ordering
>(v1
: T
, v2
: T
, compare
: F
) -> T
{
945 match compare(&v1
, &v2
) {
946 Ordering
::Less
| Ordering
::Equal
=> v1
,
947 Ordering
::Greater
=> v2
,
951 /// Returns the element that gives the minimum value from the specified function.
953 /// Returns the first argument if the comparison determines them to be equal.
958 /// #![feature(cmp_min_max_by)]
962 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
963 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
967 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
968 pub fn min_by_key
<T
, F
: FnMut(&T
) -> K
, K
: Ord
>(v1
: T
, v2
: T
, mut f
: F
) -> T
{
969 min_by(v1
, v2
, |v1
, v2
| f(v1
).cmp(&f(v2
)))
972 /// Compares and returns the maximum of two values.
974 /// Returns the second argument if the comparison determines them to be equal.
976 /// Internally uses an alias to [`Ord::max`].
983 /// assert_eq!(2, cmp::max(1, 2));
984 /// assert_eq!(2, cmp::max(2, 2));
988 #[stable(feature = "rust1", since = "1.0.0")]
989 pub fn max
<T
: Ord
>(v1
: T
, v2
: T
) -> T
{
993 /// Returns the maximum of two values with respect to the specified comparison function.
995 /// Returns the second argument if the comparison determines them to be equal.
1000 /// #![feature(cmp_min_max_by)]
1004 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1005 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1009 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1010 pub fn max_by
<T
, F
: FnOnce(&T
, &T
) -> Ordering
>(v1
: T
, v2
: T
, compare
: F
) -> T
{
1011 match compare(&v1
, &v2
) {
1012 Ordering
::Less
| Ordering
::Equal
=> v2
,
1013 Ordering
::Greater
=> v1
,
1017 /// Returns the element that gives the maximum value from the specified function.
1019 /// Returns the second argument if the comparison determines them to be equal.
1024 /// #![feature(cmp_min_max_by)]
1028 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1029 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1033 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1034 pub fn max_by_key
<T
, F
: FnMut(&T
) -> K
, K
: Ord
>(v1
: T
, v2
: T
, mut f
: F
) -> T
{
1035 max_by(v1
, v2
, |v1
, v2
| f(v1
).cmp(&f(v2
)))
1038 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1040 use crate::cmp
::Ordering
::{self, Equal, Greater, Less}
;
1041 use crate::hint
::unreachable_unchecked
;
1043 macro_rules
! partial_eq_impl
{
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl PartialEq
for $t
{
1048 fn eq(&self, other
: &$t
) -> bool { (*self) == (*other) }
1050 fn ne(&self, other
: &$t
) -> bool { (*self) != (*other) }
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl PartialEq
for () {
1058 fn eq(&self, _other
: &()) -> bool
{
1062 fn ne(&self, _other
: &()) -> bool
{
1068 bool
char usize u8 u16 u32 u64 u128
isize i8 i16 i32 i64 i128
f32 f64
1071 macro_rules
! eq_impl
{
1073 #[stable(feature = "rust1", since = "1.0.0")]
1078 eq_impl
! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1080 macro_rules
! partial_ord_impl
{
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl PartialOrd
for $t
{
1085 fn partial_cmp(&self, other
: &$t
) -> Option
<Ordering
> {
1086 match (self <= other
, self >= other
) {
1087 (false, false) => None
,
1088 (false, true) => Some(Greater
),
1089 (true, false) => Some(Less
),
1090 (true, true) => Some(Equal
),
1094 fn lt(&self, other
: &$t
) -> bool { (*self) < (*other) }
1096 fn le(&self, other
: &$t
) -> bool { (*self) <= (*other) }
1098 fn ge(&self, other
: &$t
) -> bool { (*self) >= (*other) }
1100 fn gt(&self, other
: &$t
) -> bool { (*self) > (*other) }
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl PartialOrd
for () {
1108 fn partial_cmp(&self, _
: &()) -> Option
<Ordering
> {
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl PartialOrd
for bool
{
1116 fn partial_cmp(&self, other
: &bool
) -> Option
<Ordering
> {
1117 (*self as u8).partial_cmp(&(*other
as u8))
1121 partial_ord_impl
! { f32 f64 }
1123 macro_rules
! ord_impl
{
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 impl PartialOrd
for $t
{
1128 fn partial_cmp(&self, other
: &$t
) -> Option
<Ordering
> {
1129 Some(self.cmp(other
))
1132 fn lt(&self, other
: &$t
) -> bool { (*self) < (*other) }
1134 fn le(&self, other
: &$t
) -> bool { (*self) <= (*other) }
1136 fn ge(&self, other
: &$t
) -> bool { (*self) >= (*other) }
1138 fn gt(&self, other
: &$t
) -> bool { (*self) > (*other) }
1141 #[stable(feature = "rust1", since = "1.0.0")]
1144 fn cmp(&self, other
: &$t
) -> Ordering
{
1145 // The order here is important to generate more optimal assembly.
1146 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1147 if *self < *other { Less }
1148 else if *self == *other { Equal }
1155 #[stable(feature = "rust1", since = "1.0.0")]
1158 fn cmp(&self, _other
: &()) -> Ordering
{
1163 #[stable(feature = "rust1", since = "1.0.0")]
1166 fn cmp(&self, other
: &bool
) -> Ordering
{
1167 // Casting to i8's and converting the difference to an Ordering generates
1168 // more optimal assembly.
1169 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1170 match (*self as i8) - (*other
as i8) {
1174 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1175 _
=> unsafe { unreachable_unchecked() }
,
1180 ord_impl
! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1182 #[unstable(feature = "never_type", issue = "35121")]
1183 impl PartialEq
for ! {
1184 fn eq(&self, _
: &!) -> bool
{
1189 #[unstable(feature = "never_type", issue = "35121")]
1192 #[unstable(feature = "never_type", issue = "35121")]
1193 impl PartialOrd
for ! {
1194 fn partial_cmp(&self, _
: &!) -> Option
<Ordering
> {
1199 #[unstable(feature = "never_type", issue = "35121")]
1201 fn cmp(&self, _
: &!) -> Ordering
{
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 impl<A
: ?Sized
, B
: ?Sized
> PartialEq
<&B
> for &A
1214 fn eq(&self, other
: &&B
) -> bool
{
1215 PartialEq
::eq(*self, *other
)
1218 fn ne(&self, other
: &&B
) -> bool
{
1219 PartialEq
::ne(*self, *other
)
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 impl<A
: ?Sized
, B
: ?Sized
> PartialOrd
<&B
> for &A
1228 fn partial_cmp(&self, other
: &&B
) -> Option
<Ordering
> {
1229 PartialOrd
::partial_cmp(*self, *other
)
1232 fn lt(&self, other
: &&B
) -> bool
{
1233 PartialOrd
::lt(*self, *other
)
1236 fn le(&self, other
: &&B
) -> bool
{
1237 PartialOrd
::le(*self, *other
)
1240 fn gt(&self, other
: &&B
) -> bool
{
1241 PartialOrd
::gt(*self, *other
)
1244 fn ge(&self, other
: &&B
) -> bool
{
1245 PartialOrd
::ge(*self, *other
)
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 impl<A
: ?Sized
> Ord
for &A
1254 fn cmp(&self, other
: &Self) -> Ordering
{
1255 Ord
::cmp(*self, *other
)
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<A
: ?Sized
> Eq
for &A
where A
: Eq {}
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 impl<A
: ?Sized
, B
: ?Sized
> PartialEq
<&mut B
> for &mut A
1269 fn eq(&self, other
: &&mut B
) -> bool
{
1270 PartialEq
::eq(*self, *other
)
1273 fn ne(&self, other
: &&mut B
) -> bool
{
1274 PartialEq
::ne(*self, *other
)
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<A
: ?Sized
, B
: ?Sized
> PartialOrd
<&mut B
> for &mut A
1283 fn partial_cmp(&self, other
: &&mut B
) -> Option
<Ordering
> {
1284 PartialOrd
::partial_cmp(*self, *other
)
1287 fn lt(&self, other
: &&mut B
) -> bool
{
1288 PartialOrd
::lt(*self, *other
)
1291 fn le(&self, other
: &&mut B
) -> bool
{
1292 PartialOrd
::le(*self, *other
)
1295 fn gt(&self, other
: &&mut B
) -> bool
{
1296 PartialOrd
::gt(*self, *other
)
1299 fn ge(&self, other
: &&mut B
) -> bool
{
1300 PartialOrd
::ge(*self, *other
)
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<A
: ?Sized
> Ord
for &mut A
1309 fn cmp(&self, other
: &Self) -> Ordering
{
1310 Ord
::cmp(*self, *other
)
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<A
: ?Sized
> Eq
for &mut A
where A
: Eq {}
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl<A
: ?Sized
, B
: ?Sized
> PartialEq
<&mut B
> for &A
1322 fn eq(&self, other
: &&mut B
) -> bool
{
1323 PartialEq
::eq(*self, *other
)
1326 fn ne(&self, other
: &&mut B
) -> bool
{
1327 PartialEq
::ne(*self, *other
)
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 impl<A
: ?Sized
, B
: ?Sized
> PartialEq
<&B
> for &mut A
1337 fn eq(&self, other
: &&B
) -> bool
{
1338 PartialEq
::eq(*self, *other
)
1341 fn ne(&self, other
: &&B
) -> bool
{
1342 PartialEq
::ne(*self, *other
)