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 /// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
31 /// We use the easier-to-read infix notation in the remainder of this documentation.
33 /// This trait allows for partial equality, for types that do not have a full
34 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
35 /// so floating point types implement `PartialEq` but not [`trait@Eq`].
37 /// Implementations must ensure that `eq` and `ne` are consistent with each other:
39 /// - `a != b` if and only if `!(a == b)`
40 /// (ensured by the default implementation).
42 /// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
43 /// be consistent with `PartialEq` (see the documentation of those traits for the exact
44 /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
45 /// manually implementing others.
47 /// The equality relation `==` must satisfy the following conditions
48 /// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
50 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
51 /// implies `b == a`**; and
53 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
54 /// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
56 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
57 /// (transitive) impls are not forced to exist, but these requirements apply
58 /// whenever they do exist.
62 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
63 /// instances are equal if all fields are equal, and not equal if any fields
64 /// are not equal. When `derive`d on enums, two instances are equal if they
65 /// are the same variant and all fields are equal.
67 /// ## How can I implement `PartialEq`?
69 /// An example implementation for a domain in which two books are considered
70 /// the same book if their ISBN matches, even if the formats differ:
81 /// format: BookFormat,
84 /// impl PartialEq for Book {
85 /// fn eq(&self, other: &Self) -> bool {
86 /// self.isbn == other.isbn
90 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
91 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
92 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
94 /// assert!(b1 == b2);
95 /// assert!(b1 != b3);
98 /// ## How can I compare two different types?
100 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
101 /// For example, let's tweak our previous code a bit:
104 /// // The derive implements <BookFormat> == <BookFormat> comparisons
105 /// #[derive(PartialEq)]
106 /// enum BookFormat {
114 /// format: BookFormat,
117 /// // Implement <Book> == <BookFormat> comparisons
118 /// impl PartialEq<BookFormat> for Book {
119 /// fn eq(&self, other: &BookFormat) -> bool {
120 /// self.format == *other
124 /// // Implement <BookFormat> == <Book> comparisons
125 /// impl PartialEq<Book> for BookFormat {
126 /// fn eq(&self, other: &Book) -> bool {
127 /// *self == other.format
131 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
133 /// assert!(b1 == BookFormat::Paperback);
134 /// assert!(BookFormat::Ebook != b1);
137 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
138 /// we allow `BookFormat`s to be compared with `Book`s.
140 /// A comparison like the one above, which ignores some fields of the struct,
141 /// can be dangerous. It can easily lead to an unintended violation of the
142 /// requirements for a partial equivalence relation. For example, if we kept
143 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
144 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
145 /// via the manual implementation from the first example) then the result would
146 /// violate transitivity:
149 /// #[derive(PartialEq)]
150 /// enum BookFormat {
156 /// #[derive(PartialEq)]
159 /// format: BookFormat,
162 /// impl PartialEq<BookFormat> for Book {
163 /// fn eq(&self, other: &BookFormat) -> bool {
164 /// self.format == *other
168 /// impl PartialEq<Book> for BookFormat {
169 /// fn eq(&self, other: &Book) -> bool {
170 /// *self == other.format
175 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
176 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
178 /// assert!(b1 == BookFormat::Paperback);
179 /// assert!(BookFormat::Paperback == b2);
181 /// // The following should hold by transitivity but doesn't.
182 /// assert!(b1 == b2); // <-- PANICS
192 /// assert_eq!(x == y, false);
193 /// assert_eq!(x.eq(&y), false);
196 /// [`eq`]: PartialEq::eq
197 /// [`ne`]: PartialEq::ne
199 #[stable(feature = "rust1", since = "1.0.0")]
204 rustc_on_unimplemented(
205 message = "can't compare `{Self}` with `{Rhs}`",
206 label = "no implementation for `{Self} == {Rhs}`"
211 rustc_on_unimplemented(
212 message = "can't compare `{Self}` with `{Rhs}`",
213 label = "no implementation for `{Self} == {Rhs}`",
218 #[rustc_diagnostic_item = "PartialEq"]
219 pub trait PartialEq<Rhs: ?Sized = Self> {
220 /// This method tests for `self` and `other` values to be equal, and is used
223 #[stable(feature = "rust1", since = "1.0.0")]
224 fn eq(&self, other: &Rhs) -> bool;
226 /// This method tests for `!=`.
229 #[stable(feature = "rust1", since = "1.0.0")]
230 fn ne(&self, other: &Rhs) -> bool {
235 /// Derive macro generating an impl of the trait `PartialEq`.
236 #[rustc_builtin_macro]
237 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
238 #[allow_internal_unstable(core_intrinsics, structural_match)]
239 pub macro PartialEq($item:item) {
240 /* compiler built-in */
243 /// Trait for equality comparisons which are [equivalence relations](
244 /// https://en.wikipedia.org/wiki/Equivalence_relation).
246 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
247 /// be (for all `a`, `b` and `c`):
249 /// - reflexive: `a == a`;
250 /// - symmetric: `a == b` implies `b == a`; and
251 /// - transitive: `a == b` and `b == c` implies `a == c`.
253 /// This property cannot be checked by the compiler, and therefore `Eq` implies
254 /// [`PartialEq`], and has no extra methods.
258 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
259 /// no extra methods, it is only informing the compiler that this is an
260 /// equivalence relation rather than a partial equivalence relation. Note that
261 /// the `derive` strategy requires all fields are `Eq`, which isn't
264 /// ## How can I implement `Eq`?
266 /// If you cannot use the `derive` strategy, specify that your type implements
267 /// `Eq`, which has no methods:
270 /// enum BookFormat { Paperback, Hardback, Ebook }
273 /// format: BookFormat,
275 /// impl PartialEq for Book {
276 /// fn eq(&self, other: &Self) -> bool {
277 /// self.isbn == other.isbn
280 /// impl Eq for Book {}
284 #[stable(feature = "rust1", since = "1.0.0")]
285 #[rustc_diagnostic_item = "Eq"]
286 pub trait Eq: PartialEq<Self> {
287 // this method is used solely by #[deriving] to assert
288 // that every component of a type implements #[deriving]
289 // itself, the current deriving infrastructure means doing this
290 // assertion without using a method on this trait is nearly
293 // This should never be implemented by hand.
295 #[no_coverage] // rust-lang/rust#84605
297 #[stable(feature = "rust1", since = "1.0.0")]
298 fn assert_receiver_is_total_eq(&self) {}
301 /// Derive macro generating an impl of the trait `Eq`.
302 #[rustc_builtin_macro]
303 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
304 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
305 pub macro Eq($item:item) {
306 /* compiler built-in */
309 // FIXME: this struct is used solely by #[derive] to
310 // assert that every component of a type implements Eq.
312 // This struct should never appear in user code.
314 #[allow(missing_debug_implementations)]
315 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
316 pub struct AssertParamIsEq<T: Eq + ?Sized> {
317 _field: crate::marker::PhantomData<T>,
320 /// An `Ordering` is the result of a comparison between two values.
325 /// use std::cmp::Ordering;
327 /// let result = 1.cmp(&2);
328 /// assert_eq!(Ordering::Less, result);
330 /// let result = 1.cmp(&1);
331 /// assert_eq!(Ordering::Equal, result);
333 /// let result = 2.cmp(&1);
334 /// assert_eq!(Ordering::Greater, result);
336 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
337 #[stable(feature = "rust1", since = "1.0.0")]
340 /// An ordering where a compared value is less than another.
341 #[stable(feature = "rust1", since = "1.0.0")]
343 /// An ordering where a compared value is equal to another.
344 #[stable(feature = "rust1", since = "1.0.0")]
346 /// An ordering where a compared value is greater than another.
347 #[stable(feature = "rust1", since = "1.0.0")]
352 /// Returns `true` if the ordering is the `Equal` variant.
357 /// use std::cmp::Ordering;
359 /// assert_eq!(Ordering::Less.is_eq(), false);
360 /// assert_eq!(Ordering::Equal.is_eq(), true);
361 /// assert_eq!(Ordering::Greater.is_eq(), false);
365 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
366 #[stable(feature = "ordering_helpers", since = "1.53.0")]
367 pub const fn is_eq(self) -> bool {
368 matches!(self, Equal)
371 /// Returns `true` if the ordering is not the `Equal` variant.
376 /// use std::cmp::Ordering;
378 /// assert_eq!(Ordering::Less.is_ne(), true);
379 /// assert_eq!(Ordering::Equal.is_ne(), false);
380 /// assert_eq!(Ordering::Greater.is_ne(), true);
384 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
385 #[stable(feature = "ordering_helpers", since = "1.53.0")]
386 pub const fn is_ne(self) -> bool {
387 !matches!(self, Equal)
390 /// Returns `true` if the ordering is the `Less` variant.
395 /// use std::cmp::Ordering;
397 /// assert_eq!(Ordering::Less.is_lt(), true);
398 /// assert_eq!(Ordering::Equal.is_lt(), false);
399 /// assert_eq!(Ordering::Greater.is_lt(), false);
403 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
404 #[stable(feature = "ordering_helpers", since = "1.53.0")]
405 pub const fn is_lt(self) -> bool {
409 /// Returns `true` if the ordering is the `Greater` variant.
414 /// use std::cmp::Ordering;
416 /// assert_eq!(Ordering::Less.is_gt(), false);
417 /// assert_eq!(Ordering::Equal.is_gt(), false);
418 /// assert_eq!(Ordering::Greater.is_gt(), true);
422 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
423 #[stable(feature = "ordering_helpers", since = "1.53.0")]
424 pub const fn is_gt(self) -> bool {
425 matches!(self, Greater)
428 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
433 /// use std::cmp::Ordering;
435 /// assert_eq!(Ordering::Less.is_le(), true);
436 /// assert_eq!(Ordering::Equal.is_le(), true);
437 /// assert_eq!(Ordering::Greater.is_le(), false);
441 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
442 #[stable(feature = "ordering_helpers", since = "1.53.0")]
443 pub const fn is_le(self) -> bool {
444 !matches!(self, Greater)
447 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
452 /// use std::cmp::Ordering;
454 /// assert_eq!(Ordering::Less.is_ge(), false);
455 /// assert_eq!(Ordering::Equal.is_ge(), true);
456 /// assert_eq!(Ordering::Greater.is_ge(), true);
460 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
461 #[stable(feature = "ordering_helpers", since = "1.53.0")]
462 pub const fn is_ge(self) -> bool {
463 !matches!(self, Less)
466 /// Reverses the `Ordering`.
468 /// * `Less` becomes `Greater`.
469 /// * `Greater` becomes `Less`.
470 /// * `Equal` becomes `Equal`.
477 /// use std::cmp::Ordering;
479 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
480 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
481 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
484 /// This method can be used to reverse a comparison:
487 /// let data: &mut [_] = &mut [2, 10, 5, 8];
489 /// // sort the array from largest to smallest.
490 /// data.sort_by(|a, b| a.cmp(b).reverse());
492 /// let b: &mut [_] = &mut [10, 8, 5, 2];
493 /// assert!(data == b);
497 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub const fn reverse(self) -> Ordering {
507 /// Chains two orderings.
509 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
514 /// use std::cmp::Ordering;
516 /// let result = Ordering::Equal.then(Ordering::Less);
517 /// assert_eq!(result, Ordering::Less);
519 /// let result = Ordering::Less.then(Ordering::Equal);
520 /// assert_eq!(result, Ordering::Less);
522 /// let result = Ordering::Less.then(Ordering::Greater);
523 /// assert_eq!(result, Ordering::Less);
525 /// let result = Ordering::Equal.then(Ordering::Equal);
526 /// assert_eq!(result, Ordering::Equal);
528 /// let x: (i64, i64, i64) = (1, 2, 7);
529 /// let y: (i64, i64, i64) = (1, 5, 3);
530 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
532 /// assert_eq!(result, Ordering::Less);
536 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
537 #[stable(feature = "ordering_chaining", since = "1.17.0")]
538 pub const fn then(self, other: Ordering) -> Ordering {
545 /// Chains the ordering with the given function.
547 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
553 /// use std::cmp::Ordering;
555 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
556 /// assert_eq!(result, Ordering::Less);
558 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
559 /// assert_eq!(result, Ordering::Less);
561 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
562 /// assert_eq!(result, Ordering::Less);
564 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
565 /// assert_eq!(result, Ordering::Equal);
567 /// let x: (i64, i64, i64) = (1, 2, 7);
568 /// let y: (i64, i64, i64) = (1, 5, 3);
569 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
571 /// assert_eq!(result, Ordering::Less);
575 #[stable(feature = "ordering_chaining", since = "1.17.0")]
576 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
584 /// A helper struct for reverse ordering.
586 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
587 /// can be used to reverse order a part of a key.
589 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
594 /// use std::cmp::Reverse;
596 /// let mut v = vec![1, 2, 3, 4, 5, 6];
597 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
598 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
600 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
601 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
603 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
605 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
606 impl<T: PartialOrd> PartialOrd for Reverse<T> {
608 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
609 other.0.partial_cmp(&self.0)
613 fn lt(&self, other: &Self) -> bool {
617 fn le(&self, other: &Self) -> bool {
621 fn gt(&self, other: &Self) -> bool {
625 fn ge(&self, other: &Self) -> bool {
630 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
631 impl<T: Ord> Ord for Reverse<T> {
633 fn cmp(&self, other: &Reverse<T>) -> Ordering {
638 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
639 impl<T: Clone> Clone for Reverse<T> {
641 fn clone(&self) -> Reverse<T> {
642 Reverse(self.0.clone())
646 fn clone_from(&mut self, other: &Self) {
647 self.0.clone_from(&other.0)
651 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
653 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
654 /// `max`, `min`, and `clamp` are consistent with `cmp`:
656 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
657 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
658 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
659 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
660 /// (ensured by the default implementation).
662 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
663 /// deriving some of the traits and manually implementing others.
667 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
668 /// This means that for all `a`, `b` and `c`:
670 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
671 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
675 /// This trait can be used with `#[derive]`.
677 /// When `derive`d on structs, it will produce a
678 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
679 /// based on the top-to-bottom declaration order of the struct's members.
681 /// When `derive`d on enums, variants are ordered by their discriminants.
682 /// By default, the discriminant is smallest for variants at the top, and
683 /// largest for variants at the bottom. Here's an example:
686 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
692 /// assert!(E::Top < E::Bottom);
695 /// However, manually setting the discriminants can override this default
699 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
705 /// assert!(E::Bottom < E::Top);
708 /// ## Lexicographical comparison
710 /// Lexicographical comparison is an operation with the following properties:
711 /// - Two sequences are compared element by element.
712 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
713 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
714 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
715 /// - An empty sequence is lexicographically less than any non-empty sequence.
716 /// - Two empty sequences are lexicographically equal.
718 /// ## How can I implement `Ord`?
720 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
722 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
723 /// [`cmp`] on your type's fields.
725 /// Here's an example where you want to sort people by height only, disregarding `id`
729 /// use std::cmp::Ordering;
738 /// impl Ord for Person {
739 /// fn cmp(&self, other: &Self) -> Ordering {
740 /// self.height.cmp(&other.height)
744 /// impl PartialOrd for Person {
745 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
746 /// Some(self.cmp(other))
750 /// impl PartialEq for Person {
751 /// fn eq(&self, other: &Self) -> bool {
752 /// self.height == other.height
757 /// [`cmp`]: Ord::cmp
762 #[stable(feature = "rust1", since = "1.0.0")]
763 #[rustc_diagnostic_item = "Ord"]
764 pub trait Ord: Eq + PartialOrd<Self> {
765 /// This method returns an [`Ordering`] between `self` and `other`.
767 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
768 /// `self <operator> other` if true.
773 /// use std::cmp::Ordering;
775 /// assert_eq!(5.cmp(&10), Ordering::Less);
776 /// assert_eq!(10.cmp(&5), Ordering::Greater);
777 /// assert_eq!(5.cmp(&5), Ordering::Equal);
780 #[stable(feature = "rust1", since = "1.0.0")]
781 fn cmp(&self, other: &Self) -> Ordering;
783 /// Compares and returns the maximum of two values.
785 /// Returns the second argument if the comparison determines them to be equal.
790 /// assert_eq!(2, 1.max(2));
791 /// assert_eq!(2, 2.max(2));
793 #[stable(feature = "ord_max_min", since = "1.21.0")]
796 fn max(self, other: Self) -> Self
800 max_by(self, other, Ord::cmp)
803 /// Compares and returns the minimum of two values.
805 /// Returns the first argument if the comparison determines them to be equal.
810 /// assert_eq!(1, 1.min(2));
811 /// assert_eq!(2, 2.min(2));
813 #[stable(feature = "ord_max_min", since = "1.21.0")]
816 fn min(self, other: Self) -> Self
820 min_by(self, other, Ord::cmp)
823 /// Restrict a value to a certain interval.
825 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
826 /// less than `min`. Otherwise this returns `self`.
830 /// Panics if `min > max`.
835 /// assert!((-3).clamp(-2, 1) == -2);
836 /// assert!(0.clamp(-2, 1) == 0);
837 /// assert!(2.clamp(-2, 1) == 1);
840 #[stable(feature = "clamp", since = "1.50.0")]
841 fn clamp(self, min: Self, max: Self) -> Self
848 } else if self > max {
856 /// Derive macro generating an impl of the trait `Ord`.
857 #[rustc_builtin_macro]
858 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
859 #[allow_internal_unstable(core_intrinsics)]
860 pub macro Ord($item:item) {
861 /* compiler built-in */
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl Ord for Ordering {
867 fn cmp(&self, other: &Ordering) -> Ordering {
868 (*self as i32).cmp(&(*other as i32))
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl PartialOrd for Ordering {
875 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
876 (*self as i32).partial_cmp(&(*other as i32))
880 /// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
882 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
883 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
885 /// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
886 /// The following conditions must hold:
888 /// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
889 /// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
890 /// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
891 /// 4. `a <= b` if and only if `a < b || a == b`
892 /// 5. `a >= b` if and only if `a > b || a == b`
893 /// 6. `a != b` if and only if `!(a == b)`.
895 /// Conditions 2–5 above are ensured by the default implementation.
896 /// Condition 6 is already ensured by [`PartialEq`].
898 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
899 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
900 /// easy to accidentally make them disagree by deriving some of the traits and manually
901 /// implementing others.
903 /// The comparison must satisfy, for all `a`, `b` and `c`:
905 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
906 /// - duality: `a < b` if and only if `b > a`.
908 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
909 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
914 /// The following corollaries follow from the above requirements:
916 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
917 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
918 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
922 /// This trait can be used with `#[derive]`.
924 /// When `derive`d on structs, it will produce a
925 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
926 /// based on the top-to-bottom declaration order of the struct's members.
928 /// When `derive`d on enums, variants are ordered by their discriminants.
929 /// By default, the discriminant is smallest for variants at the top, and
930 /// largest for variants at the bottom. Here's an example:
933 /// #[derive(PartialEq, PartialOrd)]
939 /// assert!(E::Top < E::Bottom);
942 /// However, manually setting the discriminants can override this default
946 /// #[derive(PartialEq, PartialOrd)]
952 /// assert!(E::Bottom < E::Top);
955 /// ## How can I implement `PartialOrd`?
957 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
958 /// generated from default implementations.
960 /// However it remains possible to implement the others separately for types which do not have a
961 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
962 /// false` (cf. IEEE 754-2008 section 5.11).
964 /// `PartialOrd` requires your type to be [`PartialEq`].
966 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
969 /// use std::cmp::Ordering;
978 /// impl PartialOrd for Person {
979 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
980 /// Some(self.cmp(other))
984 /// impl Ord for Person {
985 /// fn cmp(&self, other: &Self) -> Ordering {
986 /// self.height.cmp(&other.height)
990 /// impl PartialEq for Person {
991 /// fn eq(&self, other: &Self) -> bool {
992 /// self.height == other.height
997 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
998 /// is an example of `Person` types who have a floating-point `height` field that
999 /// is the only field to be used for sorting:
1002 /// use std::cmp::Ordering;
1010 /// impl PartialOrd for Person {
1011 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1012 /// self.height.partial_cmp(&other.height)
1016 /// impl PartialEq for Person {
1017 /// fn eq(&self, other: &Self) -> bool {
1018 /// self.height == other.height
1029 /// assert_eq!(x < y, true);
1030 /// assert_eq!(x.lt(&y), true);
1033 /// [`partial_cmp`]: PartialOrd::partial_cmp
1034 /// [`cmp`]: Ord::cmp
1035 #[lang = "partial_ord"]
1036 #[stable(feature = "rust1", since = "1.0.0")]
1039 #[doc(alias = "<=")]
1040 #[doc(alias = ">=")]
1043 rustc_on_unimplemented(
1044 message = "can't compare `{Self}` with `{Rhs}`",
1045 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1050 rustc_on_unimplemented(
1051 message = "can't compare `{Self}` with `{Rhs}`",
1052 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1057 #[rustc_diagnostic_item = "PartialOrd"]
1058 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
1059 /// This method returns an ordering between `self` and `other` values if one exists.
1064 /// use std::cmp::Ordering;
1066 /// let result = 1.0.partial_cmp(&2.0);
1067 /// assert_eq!(result, Some(Ordering::Less));
1069 /// let result = 1.0.partial_cmp(&1.0);
1070 /// assert_eq!(result, Some(Ordering::Equal));
1072 /// let result = 2.0.partial_cmp(&1.0);
1073 /// assert_eq!(result, Some(Ordering::Greater));
1076 /// When comparison is impossible:
1079 /// let result = f64::NAN.partial_cmp(&1.0);
1080 /// assert_eq!(result, None);
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1086 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1091 /// let result = 1.0 < 2.0;
1092 /// assert_eq!(result, true);
1094 /// let result = 2.0 < 1.0;
1095 /// assert_eq!(result, false);
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 fn lt(&self, other: &Rhs) -> bool {
1101 matches!(self.partial_cmp(other), Some(Less))
1104 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1110 /// let result = 1.0 <= 2.0;
1111 /// assert_eq!(result, true);
1113 /// let result = 2.0 <= 2.0;
1114 /// assert_eq!(result, true);
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 fn le(&self, other: &Rhs) -> bool {
1120 // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`.
1121 // FIXME: The root cause was fixed upstream in LLVM with:
1122 // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775
1123 // Revert this workaround once support for LLVM 12 gets dropped.
1124 !matches!(self.partial_cmp(other), None | Some(Greater))
1127 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1132 /// let result = 1.0 > 2.0;
1133 /// assert_eq!(result, false);
1135 /// let result = 2.0 > 2.0;
1136 /// assert_eq!(result, false);
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 fn gt(&self, other: &Rhs) -> bool {
1142 matches!(self.partial_cmp(other), Some(Greater))
1145 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1151 /// let result = 2.0 >= 1.0;
1152 /// assert_eq!(result, true);
1154 /// let result = 2.0 >= 2.0;
1155 /// assert_eq!(result, true);
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 fn ge(&self, other: &Rhs) -> bool {
1161 matches!(self.partial_cmp(other), Some(Greater | Equal))
1165 /// Derive macro generating an impl of the trait `PartialOrd`.
1166 #[rustc_builtin_macro]
1167 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1168 #[allow_internal_unstable(core_intrinsics)]
1169 pub macro PartialOrd($item:item) {
1170 /* compiler built-in */
1173 /// Compares and returns the minimum of two values.
1175 /// Returns the first argument if the comparison determines them to be equal.
1177 /// Internally uses an alias to [`Ord::min`].
1184 /// assert_eq!(1, cmp::min(1, 2));
1185 /// assert_eq!(2, cmp::min(2, 2));
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1191 pub fn min<T: Ord>(v1: T, v2: T) -> T {
1195 /// Returns the minimum of two values with respect to the specified comparison function.
1197 /// Returns the first argument if the comparison determines them to be equal.
1204 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1205 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1209 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1210 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1211 match compare(&v1, &v2) {
1212 Ordering::Less | Ordering::Equal => v1,
1213 Ordering::Greater => v2,
1217 /// Returns the element that gives the minimum value from the specified function.
1219 /// Returns the first argument if the comparison determines them to be equal.
1226 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1227 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1231 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1232 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1233 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1236 /// Compares and returns the maximum of two values.
1238 /// Returns the second argument if the comparison determines them to be equal.
1240 /// Internally uses an alias to [`Ord::max`].
1247 /// assert_eq!(2, cmp::max(1, 2));
1248 /// assert_eq!(2, cmp::max(2, 2));
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1254 pub fn max<T: Ord>(v1: T, v2: T) -> T {
1258 /// Returns the maximum of two values with respect to the specified comparison function.
1260 /// Returns the second argument if the comparison determines them to be equal.
1267 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1268 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1272 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1273 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1274 match compare(&v1, &v2) {
1275 Ordering::Less | Ordering::Equal => v2,
1276 Ordering::Greater => v1,
1280 /// Returns the element that gives the maximum value from the specified function.
1282 /// Returns the second argument if the comparison determines them to be equal.
1289 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1290 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1294 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1295 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1296 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1299 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1301 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1302 use crate::hint::unreachable_unchecked;
1304 macro_rules! partial_eq_impl {
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl PartialEq for $t {
1309 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1311 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl PartialEq for () {
1319 fn eq(&self, _other: &()) -> bool {
1323 fn ne(&self, _other: &()) -> bool {
1329 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1332 macro_rules! eq_impl {
1334 #[stable(feature = "rust1", since = "1.0.0")]
1339 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1341 macro_rules! partial_ord_impl {
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 impl PartialOrd for $t {
1346 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1347 match (*self <= *other, *self >= *other) {
1348 (false, false) => None,
1349 (false, true) => Some(Greater),
1350 (true, false) => Some(Less),
1351 (true, true) => Some(Equal),
1355 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1357 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1359 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1361 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 impl PartialOrd for () {
1369 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl PartialOrd for bool {
1377 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1378 Some(self.cmp(other))
1382 partial_ord_impl! { f32 f64 }
1384 macro_rules! ord_impl {
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl PartialOrd for $t {
1389 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1390 Some(self.cmp(other))
1393 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1395 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1397 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1399 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1402 #[stable(feature = "rust1", since = "1.0.0")]
1405 fn cmp(&self, other: &$t) -> Ordering {
1406 // The order here is important to generate more optimal assembly.
1407 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1408 if *self < *other { Less }
1409 else if *self == *other { Equal }
1416 #[stable(feature = "rust1", since = "1.0.0")]
1419 fn cmp(&self, _other: &()) -> Ordering {
1424 #[stable(feature = "rust1", since = "1.0.0")]
1427 fn cmp(&self, other: &bool) -> Ordering {
1428 // Casting to i8's and converting the difference to an Ordering generates
1429 // more optimal assembly.
1430 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1431 match (*self as i8) - (*other as i8) {
1435 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1436 _ => unsafe { unreachable_unchecked() },
1441 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1443 #[unstable(feature = "never_type", issue = "35121")]
1444 impl PartialEq for ! {
1445 fn eq(&self, _: &!) -> bool {
1450 #[unstable(feature = "never_type", issue = "35121")]
1453 #[unstable(feature = "never_type", issue = "35121")]
1454 impl PartialOrd for ! {
1455 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1460 #[unstable(feature = "never_type", issue = "35121")]
1462 fn cmp(&self, _: &!) -> Ordering {
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
1475 fn eq(&self, other: &&B) -> bool {
1476 PartialEq::eq(*self, *other)
1479 fn ne(&self, other: &&B) -> bool {
1480 PartialEq::ne(*self, *other)
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1489 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1490 PartialOrd::partial_cmp(*self, *other)
1493 fn lt(&self, other: &&B) -> bool {
1494 PartialOrd::lt(*self, *other)
1497 fn le(&self, other: &&B) -> bool {
1498 PartialOrd::le(*self, *other)
1501 fn gt(&self, other: &&B) -> bool {
1502 PartialOrd::gt(*self, *other)
1505 fn ge(&self, other: &&B) -> bool {
1506 PartialOrd::ge(*self, *other)
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<A: ?Sized> Ord for &A
1515 fn cmp(&self, other: &Self) -> Ordering {
1516 Ord::cmp(*self, *other)
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<A: ?Sized> Eq for &A where A: Eq {}
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1530 fn eq(&self, other: &&mut B) -> bool {
1531 PartialEq::eq(*self, *other)
1534 fn ne(&self, other: &&mut B) -> bool {
1535 PartialEq::ne(*self, *other)
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1544 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1545 PartialOrd::partial_cmp(*self, *other)
1548 fn lt(&self, other: &&mut B) -> bool {
1549 PartialOrd::lt(*self, *other)
1552 fn le(&self, other: &&mut B) -> bool {
1553 PartialOrd::le(*self, *other)
1556 fn gt(&self, other: &&mut B) -> bool {
1557 PartialOrd::gt(*self, *other)
1560 fn ge(&self, other: &&mut B) -> bool {
1561 PartialOrd::ge(*self, *other)
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 impl<A: ?Sized> Ord for &mut A
1570 fn cmp(&self, other: &Self) -> Ordering {
1571 Ord::cmp(*self, *other)
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1583 fn eq(&self, other: &&mut B) -> bool {
1584 PartialEq::eq(*self, *other)
1587 fn ne(&self, other: &&mut B) -> bool {
1588 PartialEq::ne(*self, *other)
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1598 fn eq(&self, other: &&B) -> bool {
1599 PartialEq::eq(*self, *other)
1602 fn ne(&self, other: &&B) -> bool {
1603 PartialEq::ne(*self, *other)