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}`",
217 #[cfg_attr(not(bootstrap), const_trait)]
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 #[cfg_attr(bootstrap, default_method_body_is_const)]
231 fn ne(&self, other: &Rhs) -> bool {
236 /// Derive macro generating an impl of the trait `PartialEq`.
237 #[rustc_builtin_macro]
238 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
239 #[allow_internal_unstable(core_intrinsics, structural_match)]
240 pub macro PartialEq($item:item) {
241 /* compiler built-in */
244 /// Trait for equality comparisons which are [equivalence relations](
245 /// https://en.wikipedia.org/wiki/Equivalence_relation).
247 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
248 /// be (for all `a`, `b` and `c`):
250 /// - reflexive: `a == a`;
251 /// - symmetric: `a == b` implies `b == a`; and
252 /// - transitive: `a == b` and `b == c` implies `a == c`.
254 /// This property cannot be checked by the compiler, and therefore `Eq` implies
255 /// [`PartialEq`], and has no extra methods.
259 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
260 /// no extra methods, it is only informing the compiler that this is an
261 /// equivalence relation rather than a partial equivalence relation. Note that
262 /// the `derive` strategy requires all fields are `Eq`, which isn't
265 /// ## How can I implement `Eq`?
267 /// If you cannot use the `derive` strategy, specify that your type implements
268 /// `Eq`, which has no methods:
271 /// enum BookFormat { Paperback, Hardback, Ebook }
274 /// format: BookFormat,
276 /// impl PartialEq for Book {
277 /// fn eq(&self, other: &Self) -> bool {
278 /// self.isbn == other.isbn
281 /// impl Eq for Book {}
285 #[stable(feature = "rust1", since = "1.0.0")]
286 #[rustc_diagnostic_item = "Eq"]
287 pub trait Eq: PartialEq<Self> {
288 // this method is used solely by #[deriving] to assert
289 // that every component of a type implements #[deriving]
290 // itself, the current deriving infrastructure means doing this
291 // assertion without using a method on this trait is nearly
294 // This should never be implemented by hand.
296 #[no_coverage] // rust-lang/rust#84605
298 #[stable(feature = "rust1", since = "1.0.0")]
299 fn assert_receiver_is_total_eq(&self) {}
302 /// Derive macro generating an impl of the trait `Eq`.
303 #[rustc_builtin_macro]
304 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
305 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
306 pub macro Eq($item:item) {
307 /* compiler built-in */
310 // FIXME: this struct is used solely by #[derive] to
311 // assert that every component of a type implements Eq.
313 // This struct should never appear in user code.
315 #[allow(missing_debug_implementations)]
316 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
317 pub struct AssertParamIsEq<T: Eq + ?Sized> {
318 _field: crate::marker::PhantomData<T>,
321 /// An `Ordering` is the result of a comparison between two values.
326 /// use std::cmp::Ordering;
328 /// let result = 1.cmp(&2);
329 /// assert_eq!(Ordering::Less, result);
331 /// let result = 1.cmp(&1);
332 /// assert_eq!(Ordering::Equal, result);
334 /// let result = 2.cmp(&1);
335 /// assert_eq!(Ordering::Greater, result);
337 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
338 #[stable(feature = "rust1", since = "1.0.0")]
341 /// An ordering where a compared value is less than another.
342 #[stable(feature = "rust1", since = "1.0.0")]
344 /// An ordering where a compared value is equal to another.
345 #[stable(feature = "rust1", since = "1.0.0")]
347 /// An ordering where a compared value is greater than another.
348 #[stable(feature = "rust1", since = "1.0.0")]
353 /// Returns `true` if the ordering is the `Equal` variant.
358 /// use std::cmp::Ordering;
360 /// assert_eq!(Ordering::Less.is_eq(), false);
361 /// assert_eq!(Ordering::Equal.is_eq(), true);
362 /// assert_eq!(Ordering::Greater.is_eq(), false);
366 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
367 #[stable(feature = "ordering_helpers", since = "1.53.0")]
368 pub const fn is_eq(self) -> bool {
369 matches!(self, Equal)
372 /// Returns `true` if the ordering is not the `Equal` variant.
377 /// use std::cmp::Ordering;
379 /// assert_eq!(Ordering::Less.is_ne(), true);
380 /// assert_eq!(Ordering::Equal.is_ne(), false);
381 /// assert_eq!(Ordering::Greater.is_ne(), true);
385 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
386 #[stable(feature = "ordering_helpers", since = "1.53.0")]
387 pub const fn is_ne(self) -> bool {
388 !matches!(self, Equal)
391 /// Returns `true` if the ordering is the `Less` variant.
396 /// use std::cmp::Ordering;
398 /// assert_eq!(Ordering::Less.is_lt(), true);
399 /// assert_eq!(Ordering::Equal.is_lt(), false);
400 /// assert_eq!(Ordering::Greater.is_lt(), false);
404 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
405 #[stable(feature = "ordering_helpers", since = "1.53.0")]
406 pub const fn is_lt(self) -> bool {
410 /// Returns `true` if the ordering is the `Greater` variant.
415 /// use std::cmp::Ordering;
417 /// assert_eq!(Ordering::Less.is_gt(), false);
418 /// assert_eq!(Ordering::Equal.is_gt(), false);
419 /// assert_eq!(Ordering::Greater.is_gt(), true);
423 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
424 #[stable(feature = "ordering_helpers", since = "1.53.0")]
425 pub const fn is_gt(self) -> bool {
426 matches!(self, Greater)
429 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
434 /// use std::cmp::Ordering;
436 /// assert_eq!(Ordering::Less.is_le(), true);
437 /// assert_eq!(Ordering::Equal.is_le(), true);
438 /// assert_eq!(Ordering::Greater.is_le(), false);
442 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
443 #[stable(feature = "ordering_helpers", since = "1.53.0")]
444 pub const fn is_le(self) -> bool {
445 !matches!(self, Greater)
448 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
453 /// use std::cmp::Ordering;
455 /// assert_eq!(Ordering::Less.is_ge(), false);
456 /// assert_eq!(Ordering::Equal.is_ge(), true);
457 /// assert_eq!(Ordering::Greater.is_ge(), true);
461 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
462 #[stable(feature = "ordering_helpers", since = "1.53.0")]
463 pub const fn is_ge(self) -> bool {
464 !matches!(self, Less)
467 /// Reverses the `Ordering`.
469 /// * `Less` becomes `Greater`.
470 /// * `Greater` becomes `Less`.
471 /// * `Equal` becomes `Equal`.
478 /// use std::cmp::Ordering;
480 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
481 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
482 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
485 /// This method can be used to reverse a comparison:
488 /// let data: &mut [_] = &mut [2, 10, 5, 8];
490 /// // sort the array from largest to smallest.
491 /// data.sort_by(|a, b| a.cmp(b).reverse());
493 /// let b: &mut [_] = &mut [10, 8, 5, 2];
494 /// assert!(data == b);
498 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub const fn reverse(self) -> Ordering {
508 /// Chains two orderings.
510 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
515 /// use std::cmp::Ordering;
517 /// let result = Ordering::Equal.then(Ordering::Less);
518 /// assert_eq!(result, Ordering::Less);
520 /// let result = Ordering::Less.then(Ordering::Equal);
521 /// assert_eq!(result, Ordering::Less);
523 /// let result = Ordering::Less.then(Ordering::Greater);
524 /// assert_eq!(result, Ordering::Less);
526 /// let result = Ordering::Equal.then(Ordering::Equal);
527 /// assert_eq!(result, Ordering::Equal);
529 /// let x: (i64, i64, i64) = (1, 2, 7);
530 /// let y: (i64, i64, i64) = (1, 5, 3);
531 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
533 /// assert_eq!(result, Ordering::Less);
537 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
538 #[stable(feature = "ordering_chaining", since = "1.17.0")]
539 pub const fn then(self, other: Ordering) -> Ordering {
546 /// Chains the ordering with the given function.
548 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
554 /// use std::cmp::Ordering;
556 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
557 /// assert_eq!(result, Ordering::Less);
559 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
560 /// assert_eq!(result, Ordering::Less);
562 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
563 /// assert_eq!(result, Ordering::Less);
565 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
566 /// assert_eq!(result, Ordering::Equal);
568 /// let x: (i64, i64, i64) = (1, 2, 7);
569 /// let y: (i64, i64, i64) = (1, 5, 3);
570 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
572 /// assert_eq!(result, Ordering::Less);
576 #[stable(feature = "ordering_chaining", since = "1.17.0")]
577 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
585 /// A helper struct for reverse ordering.
587 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
588 /// can be used to reverse order a part of a key.
590 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
595 /// use std::cmp::Reverse;
597 /// let mut v = vec![1, 2, 3, 4, 5, 6];
598 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
599 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
601 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
602 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
604 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
606 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
607 impl<T: PartialOrd> PartialOrd for Reverse<T> {
609 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
610 other.0.partial_cmp(&self.0)
614 fn lt(&self, other: &Self) -> bool {
618 fn le(&self, other: &Self) -> bool {
622 fn gt(&self, other: &Self) -> bool {
626 fn ge(&self, other: &Self) -> bool {
631 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
632 impl<T: Ord> Ord for Reverse<T> {
634 fn cmp(&self, other: &Reverse<T>) -> Ordering {
639 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
640 impl<T: Clone> Clone for Reverse<T> {
642 fn clone(&self) -> Reverse<T> {
643 Reverse(self.0.clone())
647 fn clone_from(&mut self, other: &Self) {
648 self.0.clone_from(&other.0)
652 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
654 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
655 /// `max`, `min`, and `clamp` are consistent with `cmp`:
657 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
658 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
659 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
660 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
661 /// (ensured by the default implementation).
663 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
664 /// deriving some of the traits and manually implementing others.
668 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
669 /// This means that for all `a`, `b` and `c`:
671 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
672 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
676 /// This trait can be used with `#[derive]`.
678 /// When `derive`d on structs, it will produce a
679 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
680 /// based on the top-to-bottom declaration order of the struct's members.
682 /// When `derive`d on enums, variants are ordered by their discriminants.
683 /// By default, the discriminant is smallest for variants at the top, and
684 /// largest for variants at the bottom. Here's an example:
687 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
693 /// assert!(E::Top < E::Bottom);
696 /// However, manually setting the discriminants can override this default
700 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
706 /// assert!(E::Bottom < E::Top);
709 /// ## Lexicographical comparison
711 /// Lexicographical comparison is an operation with the following properties:
712 /// - Two sequences are compared element by element.
713 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
714 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
715 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
716 /// - An empty sequence is lexicographically less than any non-empty sequence.
717 /// - Two empty sequences are lexicographically equal.
719 /// ## How can I implement `Ord`?
721 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
723 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
724 /// [`cmp`] on your type's fields.
726 /// Here's an example where you want to sort people by height only, disregarding `id`
730 /// use std::cmp::Ordering;
739 /// impl Ord for Person {
740 /// fn cmp(&self, other: &Self) -> Ordering {
741 /// self.height.cmp(&other.height)
745 /// impl PartialOrd for Person {
746 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
747 /// Some(self.cmp(other))
751 /// impl PartialEq for Person {
752 /// fn eq(&self, other: &Self) -> bool {
753 /// self.height == other.height
758 /// [`cmp`]: Ord::cmp
763 #[stable(feature = "rust1", since = "1.0.0")]
764 #[rustc_diagnostic_item = "Ord"]
765 pub trait Ord: Eq + PartialOrd<Self> {
766 /// This method returns an [`Ordering`] between `self` and `other`.
768 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
769 /// `self <operator> other` if true.
774 /// use std::cmp::Ordering;
776 /// assert_eq!(5.cmp(&10), Ordering::Less);
777 /// assert_eq!(10.cmp(&5), Ordering::Greater);
778 /// assert_eq!(5.cmp(&5), Ordering::Equal);
781 #[stable(feature = "rust1", since = "1.0.0")]
782 fn cmp(&self, other: &Self) -> Ordering;
784 /// Compares and returns the maximum of two values.
786 /// Returns the second argument if the comparison determines them to be equal.
791 /// assert_eq!(2, 1.max(2));
792 /// assert_eq!(2, 2.max(2));
794 #[stable(feature = "ord_max_min", since = "1.21.0")]
797 fn max(self, other: Self) -> Self
801 max_by(self, other, Ord::cmp)
804 /// Compares and returns the minimum of two values.
806 /// Returns the first argument if the comparison determines them to be equal.
811 /// assert_eq!(1, 1.min(2));
812 /// assert_eq!(2, 2.min(2));
814 #[stable(feature = "ord_max_min", since = "1.21.0")]
817 fn min(self, other: Self) -> Self
821 min_by(self, other, Ord::cmp)
824 /// Restrict a value to a certain interval.
826 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
827 /// less than `min`. Otherwise this returns `self`.
831 /// Panics if `min > max`.
836 /// assert!((-3).clamp(-2, 1) == -2);
837 /// assert!(0.clamp(-2, 1) == 0);
838 /// assert!(2.clamp(-2, 1) == 1);
841 #[stable(feature = "clamp", since = "1.50.0")]
842 fn clamp(self, min: Self, max: Self) -> Self
849 } else if self > max {
857 /// Derive macro generating an impl of the trait `Ord`.
858 #[rustc_builtin_macro]
859 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
860 #[allow_internal_unstable(core_intrinsics)]
861 pub macro Ord($item:item) {
862 /* compiler built-in */
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl Ord for Ordering {
868 fn cmp(&self, other: &Ordering) -> Ordering {
869 (*self as i32).cmp(&(*other as i32))
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl PartialOrd for Ordering {
876 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
877 (*self as i32).partial_cmp(&(*other as i32))
881 /// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
883 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
884 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
886 /// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
887 /// The following conditions must hold:
889 /// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
890 /// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
891 /// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
892 /// 4. `a <= b` if and only if `a < b || a == b`
893 /// 5. `a >= b` if and only if `a > b || a == b`
894 /// 6. `a != b` if and only if `!(a == b)`.
896 /// Conditions 2–5 above are ensured by the default implementation.
897 /// Condition 6 is already ensured by [`PartialEq`].
899 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
900 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
901 /// easy to accidentally make them disagree by deriving some of the traits and manually
902 /// implementing others.
904 /// The comparison must satisfy, for all `a`, `b` and `c`:
906 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
907 /// - duality: `a < b` if and only if `b > a`.
909 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
910 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
915 /// The following corollaries follow from the above requirements:
917 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
918 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
919 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
923 /// This trait can be used with `#[derive]`.
925 /// When `derive`d on structs, it will produce a
926 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
927 /// based on the top-to-bottom declaration order of the struct's members.
929 /// When `derive`d on enums, variants are ordered by their discriminants.
930 /// By default, the discriminant is smallest for variants at the top, and
931 /// largest for variants at the bottom. Here's an example:
934 /// #[derive(PartialEq, PartialOrd)]
940 /// assert!(E::Top < E::Bottom);
943 /// However, manually setting the discriminants can override this default
947 /// #[derive(PartialEq, PartialOrd)]
953 /// assert!(E::Bottom < E::Top);
956 /// ## How can I implement `PartialOrd`?
958 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
959 /// generated from default implementations.
961 /// However it remains possible to implement the others separately for types which do not have a
962 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
963 /// false` (cf. IEEE 754-2008 section 5.11).
965 /// `PartialOrd` requires your type to be [`PartialEq`].
967 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
970 /// use std::cmp::Ordering;
979 /// impl PartialOrd for Person {
980 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
981 /// Some(self.cmp(other))
985 /// impl Ord for Person {
986 /// fn cmp(&self, other: &Self) -> Ordering {
987 /// self.height.cmp(&other.height)
991 /// impl PartialEq for Person {
992 /// fn eq(&self, other: &Self) -> bool {
993 /// self.height == other.height
998 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
999 /// is an example of `Person` types who have a floating-point `height` field that
1000 /// is the only field to be used for sorting:
1003 /// use std::cmp::Ordering;
1011 /// impl PartialOrd for Person {
1012 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1013 /// self.height.partial_cmp(&other.height)
1017 /// impl PartialEq for Person {
1018 /// fn eq(&self, other: &Self) -> bool {
1019 /// self.height == other.height
1030 /// assert_eq!(x < y, true);
1031 /// assert_eq!(x.lt(&y), true);
1034 /// [`partial_cmp`]: PartialOrd::partial_cmp
1035 /// [`cmp`]: Ord::cmp
1036 #[lang = "partial_ord"]
1037 #[stable(feature = "rust1", since = "1.0.0")]
1040 #[doc(alias = "<=")]
1041 #[doc(alias = ">=")]
1044 rustc_on_unimplemented(
1045 message = "can't compare `{Self}` with `{Rhs}`",
1046 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1051 rustc_on_unimplemented(
1052 message = "can't compare `{Self}` with `{Rhs}`",
1053 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1057 #[cfg_attr(not(bootstrap), const_trait)]
1058 #[rustc_diagnostic_item = "PartialOrd"]
1059 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
1060 /// This method returns an ordering between `self` and `other` values if one exists.
1065 /// use std::cmp::Ordering;
1067 /// let result = 1.0.partial_cmp(&2.0);
1068 /// assert_eq!(result, Some(Ordering::Less));
1070 /// let result = 1.0.partial_cmp(&1.0);
1071 /// assert_eq!(result, Some(Ordering::Equal));
1073 /// let result = 2.0.partial_cmp(&1.0);
1074 /// assert_eq!(result, Some(Ordering::Greater));
1077 /// When comparison is impossible:
1080 /// let result = f64::NAN.partial_cmp(&1.0);
1081 /// assert_eq!(result, None);
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1087 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1092 /// let result = 1.0 < 2.0;
1093 /// assert_eq!(result, true);
1095 /// let result = 2.0 < 1.0;
1096 /// assert_eq!(result, false);
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 #[cfg_attr(bootstrap, default_method_body_is_const)]
1102 fn lt(&self, other: &Rhs) -> bool {
1103 matches!(self.partial_cmp(other), Some(Less))
1106 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1112 /// let result = 1.0 <= 2.0;
1113 /// assert_eq!(result, true);
1115 /// let result = 2.0 <= 2.0;
1116 /// assert_eq!(result, true);
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 #[cfg_attr(bootstrap, default_method_body_is_const)]
1122 fn le(&self, other: &Rhs) -> bool {
1123 // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`.
1124 // FIXME: The root cause was fixed upstream in LLVM with:
1125 // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775
1126 // Revert this workaround once support for LLVM 12 gets dropped.
1127 !matches!(self.partial_cmp(other), None | Some(Greater))
1130 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1135 /// let result = 1.0 > 2.0;
1136 /// assert_eq!(result, false);
1138 /// let result = 2.0 > 2.0;
1139 /// assert_eq!(result, false);
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 #[cfg_attr(bootstrap, default_method_body_is_const)]
1145 fn gt(&self, other: &Rhs) -> bool {
1146 matches!(self.partial_cmp(other), Some(Greater))
1149 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1155 /// let result = 2.0 >= 1.0;
1156 /// assert_eq!(result, true);
1158 /// let result = 2.0 >= 2.0;
1159 /// assert_eq!(result, true);
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 #[cfg_attr(bootstrap, default_method_body_is_const)]
1165 fn ge(&self, other: &Rhs) -> bool {
1166 matches!(self.partial_cmp(other), Some(Greater | Equal))
1170 /// Derive macro generating an impl of the trait `PartialOrd`.
1171 #[rustc_builtin_macro]
1172 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1173 #[allow_internal_unstable(core_intrinsics)]
1174 pub macro PartialOrd($item:item) {
1175 /* compiler built-in */
1178 /// Compares and returns the minimum of two values.
1180 /// Returns the first argument if the comparison determines them to be equal.
1182 /// Internally uses an alias to [`Ord::min`].
1189 /// assert_eq!(1, cmp::min(1, 2));
1190 /// assert_eq!(2, cmp::min(2, 2));
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1196 pub fn min<T: Ord>(v1: T, v2: T) -> T {
1200 /// Returns the minimum of two values with respect to the specified comparison function.
1202 /// Returns the first argument if the comparison determines them to be equal.
1209 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1210 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1214 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1215 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1216 match compare(&v1, &v2) {
1217 Ordering::Less | Ordering::Equal => v1,
1218 Ordering::Greater => v2,
1222 /// Returns the element that gives the minimum value from the specified function.
1224 /// Returns the first argument if the comparison determines them to be equal.
1231 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1232 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1236 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1237 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1238 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1241 /// Compares and returns the maximum of two values.
1243 /// Returns the second argument if the comparison determines them to be equal.
1245 /// Internally uses an alias to [`Ord::max`].
1252 /// assert_eq!(2, cmp::max(1, 2));
1253 /// assert_eq!(2, cmp::max(2, 2));
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1259 pub fn max<T: Ord>(v1: T, v2: T) -> T {
1263 /// Returns the maximum of two values with respect to the specified comparison function.
1265 /// Returns the second argument if the comparison determines them to be equal.
1272 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1273 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1277 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1278 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1279 match compare(&v1, &v2) {
1280 Ordering::Less | Ordering::Equal => v2,
1281 Ordering::Greater => v1,
1285 /// Returns the element that gives the maximum value from the specified function.
1287 /// Returns the second argument if the comparison determines them to be equal.
1294 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1295 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1299 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1300 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1301 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1304 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1306 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1307 use crate::hint::unreachable_unchecked;
1309 macro_rules! partial_eq_impl {
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl PartialEq for $t {
1314 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1316 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl PartialEq for () {
1324 fn eq(&self, _other: &()) -> bool {
1328 fn ne(&self, _other: &()) -> bool {
1334 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1337 macro_rules! eq_impl {
1339 #[stable(feature = "rust1", since = "1.0.0")]
1344 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1346 macro_rules! partial_ord_impl {
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl PartialOrd for $t {
1351 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1352 match (*self <= *other, *self >= *other) {
1353 (false, false) => None,
1354 (false, true) => Some(Greater),
1355 (true, false) => Some(Less),
1356 (true, true) => Some(Equal),
1360 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1362 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1364 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1366 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl PartialOrd for () {
1374 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl PartialOrd for bool {
1382 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1383 Some(self.cmp(other))
1387 partial_ord_impl! { f32 f64 }
1389 macro_rules! ord_impl {
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 impl PartialOrd for $t {
1394 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1395 Some(self.cmp(other))
1398 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1400 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1402 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1404 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1407 #[stable(feature = "rust1", since = "1.0.0")]
1410 fn cmp(&self, other: &$t) -> Ordering {
1411 // The order here is important to generate more optimal assembly.
1412 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1413 if *self < *other { Less }
1414 else if *self == *other { Equal }
1421 #[stable(feature = "rust1", since = "1.0.0")]
1424 fn cmp(&self, _other: &()) -> Ordering {
1429 #[stable(feature = "rust1", since = "1.0.0")]
1432 fn cmp(&self, other: &bool) -> Ordering {
1433 // Casting to i8's and converting the difference to an Ordering generates
1434 // more optimal assembly.
1435 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1436 match (*self as i8) - (*other as i8) {
1440 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1441 _ => unsafe { unreachable_unchecked() },
1446 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1448 #[unstable(feature = "never_type", issue = "35121")]
1449 impl PartialEq for ! {
1450 fn eq(&self, _: &!) -> bool {
1455 #[unstable(feature = "never_type", issue = "35121")]
1458 #[unstable(feature = "never_type", issue = "35121")]
1459 impl PartialOrd for ! {
1460 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1465 #[unstable(feature = "never_type", issue = "35121")]
1467 fn cmp(&self, _: &!) -> Ordering {
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
1480 fn eq(&self, other: &&B) -> bool {
1481 PartialEq::eq(*self, *other)
1484 fn ne(&self, other: &&B) -> bool {
1485 PartialEq::ne(*self, *other)
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1494 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1495 PartialOrd::partial_cmp(*self, *other)
1498 fn lt(&self, other: &&B) -> bool {
1499 PartialOrd::lt(*self, *other)
1502 fn le(&self, other: &&B) -> bool {
1503 PartialOrd::le(*self, *other)
1506 fn gt(&self, other: &&B) -> bool {
1507 PartialOrd::gt(*self, *other)
1510 fn ge(&self, other: &&B) -> bool {
1511 PartialOrd::ge(*self, *other)
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<A: ?Sized> Ord for &A
1520 fn cmp(&self, other: &Self) -> Ordering {
1521 Ord::cmp(*self, *other)
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 impl<A: ?Sized> Eq for &A where A: Eq {}
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1535 fn eq(&self, other: &&mut B) -> bool {
1536 PartialEq::eq(*self, *other)
1539 fn ne(&self, other: &&mut B) -> bool {
1540 PartialEq::ne(*self, *other)
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1549 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1550 PartialOrd::partial_cmp(*self, *other)
1553 fn lt(&self, other: &&mut B) -> bool {
1554 PartialOrd::lt(*self, *other)
1557 fn le(&self, other: &&mut B) -> bool {
1558 PartialOrd::le(*self, *other)
1561 fn gt(&self, other: &&mut B) -> bool {
1562 PartialOrd::gt(*self, *other)
1565 fn ge(&self, other: &&mut B) -> bool {
1566 PartialOrd::ge(*self, *other)
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<A: ?Sized> Ord for &mut A
1575 fn cmp(&self, other: &Self) -> Ordering {
1576 Ord::cmp(*self, *other)
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1588 fn eq(&self, other: &&mut B) -> bool {
1589 PartialEq::eq(*self, *other)
1592 fn ne(&self, other: &&mut B) -> bool {
1593 PartialEq::ne(*self, *other)
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1603 fn eq(&self, other: &&B) -> bool {
1604 PartialEq::eq(*self, *other)
1607 fn ne(&self, other: &&B) -> bool {
1608 PartialEq::ne(*self, *other)