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, each variant is equal to itself
65 /// and not equal to the other variants.
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")]
202 #[rustc_on_unimplemented(
203 message = "can't compare `{Self}` with `{Rhs}`",
204 label = "no implementation for `{Self} == {Rhs}`"
206 #[rustc_diagnostic_item = "PartialEq"]
207 pub trait PartialEq<Rhs: ?Sized = Self> {
208 /// This method tests for `self` and `other` values to be equal, and is used
211 #[stable(feature = "rust1", since = "1.0.0")]
212 fn eq(&self, other: &Rhs) -> bool;
214 /// This method tests for `!=`.
217 #[stable(feature = "rust1", since = "1.0.0")]
218 fn ne(&self, other: &Rhs) -> bool {
223 /// Derive macro generating an impl of the trait `PartialEq`.
224 #[rustc_builtin_macro]
225 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
226 #[allow_internal_unstable(core_intrinsics, structural_match)]
227 pub macro PartialEq($item:item) {
228 /* compiler built-in */
231 /// Trait for equality comparisons which are [equivalence relations](
232 /// https://en.wikipedia.org/wiki/Equivalence_relation).
234 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
235 /// be (for all `a`, `b` and `c`):
237 /// - reflexive: `a == a`;
238 /// - symmetric: `a == b` implies `b == a`; and
239 /// - transitive: `a == b` and `b == c` implies `a == c`.
241 /// This property cannot be checked by the compiler, and therefore `Eq` implies
242 /// [`PartialEq`], and has no extra methods.
246 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
247 /// no extra methods, it is only informing the compiler that this is an
248 /// equivalence relation rather than a partial equivalence relation. Note that
249 /// the `derive` strategy requires all fields are `Eq`, which isn't
252 /// ## How can I implement `Eq`?
254 /// If you cannot use the `derive` strategy, specify that your type implements
255 /// `Eq`, which has no methods:
258 /// enum BookFormat { Paperback, Hardback, Ebook }
261 /// format: BookFormat,
263 /// impl PartialEq for Book {
264 /// fn eq(&self, other: &Self) -> bool {
265 /// self.isbn == other.isbn
268 /// impl Eq for Book {}
272 #[stable(feature = "rust1", since = "1.0.0")]
273 #[rustc_diagnostic_item = "Eq"]
274 pub trait Eq: PartialEq<Self> {
275 // this method is used solely by #[deriving] to assert
276 // that every component of a type implements #[deriving]
277 // itself, the current deriving infrastructure means doing this
278 // assertion without using a method on this trait is nearly
281 // This should never be implemented by hand.
283 #[no_coverage] // rust-lang/rust#84605
285 #[stable(feature = "rust1", since = "1.0.0")]
286 fn assert_receiver_is_total_eq(&self) {}
289 /// Derive macro generating an impl of the trait `Eq`.
290 #[rustc_builtin_macro]
291 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
292 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
293 pub macro Eq($item:item) {
294 /* compiler built-in */
297 // FIXME: this struct is used solely by #[derive] to
298 // assert that every component of a type implements Eq.
300 // This struct should never appear in user code.
302 #[allow(missing_debug_implementations)]
303 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
304 pub struct AssertParamIsEq<T: Eq + ?Sized> {
305 _field: crate::marker::PhantomData<T>,
308 /// An `Ordering` is the result of a comparison between two values.
313 /// use std::cmp::Ordering;
315 /// let result = 1.cmp(&2);
316 /// assert_eq!(Ordering::Less, result);
318 /// let result = 1.cmp(&1);
319 /// assert_eq!(Ordering::Equal, result);
321 /// let result = 2.cmp(&1);
322 /// assert_eq!(Ordering::Greater, result);
324 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
325 #[stable(feature = "rust1", since = "1.0.0")]
328 /// An ordering where a compared value is less than another.
329 #[stable(feature = "rust1", since = "1.0.0")]
331 /// An ordering where a compared value is equal to another.
332 #[stable(feature = "rust1", since = "1.0.0")]
334 /// An ordering where a compared value is greater than another.
335 #[stable(feature = "rust1", since = "1.0.0")]
340 /// Returns `true` if the ordering is the `Equal` variant.
345 /// use std::cmp::Ordering;
347 /// assert_eq!(Ordering::Less.is_eq(), false);
348 /// assert_eq!(Ordering::Equal.is_eq(), true);
349 /// assert_eq!(Ordering::Greater.is_eq(), false);
353 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
354 #[stable(feature = "ordering_helpers", since = "1.53.0")]
355 pub const fn is_eq(self) -> bool {
356 matches!(self, Equal)
359 /// Returns `true` if the ordering is not the `Equal` variant.
364 /// use std::cmp::Ordering;
366 /// assert_eq!(Ordering::Less.is_ne(), true);
367 /// assert_eq!(Ordering::Equal.is_ne(), false);
368 /// assert_eq!(Ordering::Greater.is_ne(), true);
372 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
373 #[stable(feature = "ordering_helpers", since = "1.53.0")]
374 pub const fn is_ne(self) -> bool {
375 !matches!(self, Equal)
378 /// Returns `true` if the ordering is the `Less` variant.
383 /// use std::cmp::Ordering;
385 /// assert_eq!(Ordering::Less.is_lt(), true);
386 /// assert_eq!(Ordering::Equal.is_lt(), false);
387 /// assert_eq!(Ordering::Greater.is_lt(), false);
391 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
392 #[stable(feature = "ordering_helpers", since = "1.53.0")]
393 pub const fn is_lt(self) -> bool {
397 /// Returns `true` if the ordering is the `Greater` variant.
402 /// use std::cmp::Ordering;
404 /// assert_eq!(Ordering::Less.is_gt(), false);
405 /// assert_eq!(Ordering::Equal.is_gt(), false);
406 /// assert_eq!(Ordering::Greater.is_gt(), true);
410 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
411 #[stable(feature = "ordering_helpers", since = "1.53.0")]
412 pub const fn is_gt(self) -> bool {
413 matches!(self, Greater)
416 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
421 /// use std::cmp::Ordering;
423 /// assert_eq!(Ordering::Less.is_le(), true);
424 /// assert_eq!(Ordering::Equal.is_le(), true);
425 /// assert_eq!(Ordering::Greater.is_le(), false);
429 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
430 #[stable(feature = "ordering_helpers", since = "1.53.0")]
431 pub const fn is_le(self) -> bool {
432 !matches!(self, Greater)
435 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
440 /// use std::cmp::Ordering;
442 /// assert_eq!(Ordering::Less.is_ge(), false);
443 /// assert_eq!(Ordering::Equal.is_ge(), true);
444 /// assert_eq!(Ordering::Greater.is_ge(), true);
448 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
449 #[stable(feature = "ordering_helpers", since = "1.53.0")]
450 pub const fn is_ge(self) -> bool {
451 !matches!(self, Less)
454 /// Reverses the `Ordering`.
456 /// * `Less` becomes `Greater`.
457 /// * `Greater` becomes `Less`.
458 /// * `Equal` becomes `Equal`.
465 /// use std::cmp::Ordering;
467 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
468 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
469 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
472 /// This method can be used to reverse a comparison:
475 /// let data: &mut [_] = &mut [2, 10, 5, 8];
477 /// // sort the array from largest to smallest.
478 /// data.sort_by(|a, b| a.cmp(b).reverse());
480 /// let b: &mut [_] = &mut [10, 8, 5, 2];
481 /// assert!(data == b);
485 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub const fn reverse(self) -> Ordering {
495 /// Chains two orderings.
497 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
502 /// use std::cmp::Ordering;
504 /// let result = Ordering::Equal.then(Ordering::Less);
505 /// assert_eq!(result, Ordering::Less);
507 /// let result = Ordering::Less.then(Ordering::Equal);
508 /// assert_eq!(result, Ordering::Less);
510 /// let result = Ordering::Less.then(Ordering::Greater);
511 /// assert_eq!(result, Ordering::Less);
513 /// let result = Ordering::Equal.then(Ordering::Equal);
514 /// assert_eq!(result, Ordering::Equal);
516 /// let x: (i64, i64, i64) = (1, 2, 7);
517 /// let y: (i64, i64, i64) = (1, 5, 3);
518 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
520 /// assert_eq!(result, Ordering::Less);
524 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
525 #[stable(feature = "ordering_chaining", since = "1.17.0")]
526 pub const fn then(self, other: Ordering) -> Ordering {
533 /// Chains the ordering with the given function.
535 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
541 /// use std::cmp::Ordering;
543 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
544 /// assert_eq!(result, Ordering::Less);
546 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
547 /// assert_eq!(result, Ordering::Less);
549 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
550 /// assert_eq!(result, Ordering::Less);
552 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
553 /// assert_eq!(result, Ordering::Equal);
555 /// let x: (i64, i64, i64) = (1, 2, 7);
556 /// let y: (i64, i64, i64) = (1, 5, 3);
557 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
559 /// assert_eq!(result, Ordering::Less);
563 #[stable(feature = "ordering_chaining", since = "1.17.0")]
564 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
572 /// A helper struct for reverse ordering.
574 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
575 /// can be used to reverse order a part of a key.
577 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
582 /// use std::cmp::Reverse;
584 /// let mut v = vec![1, 2, 3, 4, 5, 6];
585 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
586 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
588 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
589 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
591 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
593 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
594 impl<T: PartialOrd> PartialOrd for Reverse<T> {
596 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
597 other.0.partial_cmp(&self.0)
601 fn lt(&self, other: &Self) -> bool {
605 fn le(&self, other: &Self) -> bool {
609 fn gt(&self, other: &Self) -> bool {
613 fn ge(&self, other: &Self) -> bool {
618 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
619 impl<T: Ord> Ord for Reverse<T> {
621 fn cmp(&self, other: &Reverse<T>) -> Ordering {
626 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
627 impl<T: Clone> Clone for Reverse<T> {
629 fn clone(&self) -> Reverse<T> {
630 Reverse(self.0.clone())
634 fn clone_from(&mut self, other: &Self) {
635 self.0.clone_from(&other.0)
639 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
641 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
642 /// `max`, `min`, and `clamp` are consistent with `cmp`:
644 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
645 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
646 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
647 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
648 /// (ensured by the default implementation).
650 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
651 /// deriving some of the traits and manually implementing others.
655 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
656 /// This means that for all `a`, `b` and `c`:
658 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
659 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
663 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
664 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the top-to-bottom declaration order of the struct's members.
665 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
666 /// This means variants at the top are less than variants at the bottom.
667 /// Here's an example:
670 /// #[derive(PartialEq, PartialOrd)]
676 /// assert!(Size::Small < Size::Large);
679 /// ## Lexicographical comparison
681 /// Lexicographical comparison is an operation with the following properties:
682 /// - Two sequences are compared element by element.
683 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
684 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
685 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
686 /// - An empty sequence is lexicographically less than any non-empty sequence.
687 /// - Two empty sequences are lexicographically equal.
689 /// ## How can I implement `Ord`?
691 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
693 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
694 /// [`cmp`] on your type's fields.
696 /// Here's an example where you want to sort people by height only, disregarding `id`
700 /// use std::cmp::Ordering;
709 /// impl Ord for Person {
710 /// fn cmp(&self, other: &Self) -> Ordering {
711 /// self.height.cmp(&other.height)
715 /// impl PartialOrd for Person {
716 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
717 /// Some(self.cmp(other))
721 /// impl PartialEq for Person {
722 /// fn eq(&self, other: &Self) -> bool {
723 /// self.height == other.height
728 /// [`cmp`]: Ord::cmp
733 #[stable(feature = "rust1", since = "1.0.0")]
734 #[rustc_diagnostic_item = "Ord"]
735 pub trait Ord: Eq + PartialOrd<Self> {
736 /// This method returns an [`Ordering`] between `self` and `other`.
738 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
739 /// `self <operator> other` if true.
744 /// use std::cmp::Ordering;
746 /// assert_eq!(5.cmp(&10), Ordering::Less);
747 /// assert_eq!(10.cmp(&5), Ordering::Greater);
748 /// assert_eq!(5.cmp(&5), Ordering::Equal);
751 #[stable(feature = "rust1", since = "1.0.0")]
752 fn cmp(&self, other: &Self) -> Ordering;
754 /// Compares and returns the maximum of two values.
756 /// Returns the second argument if the comparison determines them to be equal.
761 /// assert_eq!(2, 1.max(2));
762 /// assert_eq!(2, 2.max(2));
764 #[stable(feature = "ord_max_min", since = "1.21.0")]
767 fn max(self, other: Self) -> Self
771 max_by(self, other, Ord::cmp)
774 /// Compares and returns the minimum of two values.
776 /// Returns the first argument if the comparison determines them to be equal.
781 /// assert_eq!(1, 1.min(2));
782 /// assert_eq!(2, 2.min(2));
784 #[stable(feature = "ord_max_min", since = "1.21.0")]
787 fn min(self, other: Self) -> Self
791 min_by(self, other, Ord::cmp)
794 /// Restrict a value to a certain interval.
796 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
797 /// less than `min`. Otherwise this returns `self`.
801 /// Panics if `min > max`.
806 /// assert!((-3).clamp(-2, 1) == -2);
807 /// assert!(0.clamp(-2, 1) == 0);
808 /// assert!(2.clamp(-2, 1) == 1);
811 #[stable(feature = "clamp", since = "1.50.0")]
812 fn clamp(self, min: Self, max: Self) -> Self
819 } else if self > max {
827 /// Derive macro generating an impl of the trait `Ord`.
828 #[rustc_builtin_macro]
829 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
830 #[allow_internal_unstable(core_intrinsics)]
831 pub macro Ord($item:item) {
832 /* compiler built-in */
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl Eq for Ordering {}
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl Ord for Ordering {
841 fn cmp(&self, other: &Ordering) -> Ordering {
842 (*self as i32).cmp(&(*other as i32))
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl PartialOrd for Ordering {
849 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
850 (*self as i32).partial_cmp(&(*other as i32))
854 /// Trait for values that can be compared for a sort-order.
856 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
857 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
859 /// The methods of this trait must be consistent with each other and with those of `PartialEq` in
860 /// the following sense:
862 /// - `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
863 /// - `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
864 /// (ensured by the default implementation).
865 /// - `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
866 /// (ensured by the default implementation).
867 /// - `a <= b` if and only if `a < b || a == b`
868 /// (ensured by the default implementation).
869 /// - `a >= b` if and only if `a > b || a == b`
870 /// (ensured by the default implementation).
871 /// - `a != b` if and only if `!(a == b)` (already part of `PartialEq`).
873 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
874 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
875 /// easy to accidentally make them disagree by deriving some of the traits and manually
876 /// implementing others.
878 /// The comparison must satisfy, for all `a`, `b` and `c`:
880 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
881 /// - duality: `a < b` if and only if `b > a`.
883 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
884 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
889 /// The following corollaries follow from the above requirements:
891 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
892 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
893 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
897 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
898 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
899 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
901 /// ## How can I implement `PartialOrd`?
903 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
904 /// generated from default implementations.
906 /// However it remains possible to implement the others separately for types which do not have a
907 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
908 /// false` (cf. IEEE 754-2008 section 5.11).
910 /// `PartialOrd` requires your type to be [`PartialEq`].
912 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
915 /// use std::cmp::Ordering;
924 /// impl PartialOrd for Person {
925 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
926 /// Some(self.cmp(other))
930 /// impl Ord for Person {
931 /// fn cmp(&self, other: &Self) -> Ordering {
932 /// self.height.cmp(&other.height)
936 /// impl PartialEq for Person {
937 /// fn eq(&self, other: &Self) -> bool {
938 /// self.height == other.height
943 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
944 /// is an example of `Person` types who have a floating-point `height` field that
945 /// is the only field to be used for sorting:
948 /// use std::cmp::Ordering;
956 /// impl PartialOrd for Person {
957 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
958 /// self.height.partial_cmp(&other.height)
962 /// impl PartialEq for Person {
963 /// fn eq(&self, other: &Self) -> bool {
964 /// self.height == other.height
975 /// assert_eq!(x < y, true);
976 /// assert_eq!(x.lt(&y), true);
979 /// [`partial_cmp`]: PartialOrd::partial_cmp
980 /// [`cmp`]: Ord::cmp
981 #[lang = "partial_ord"]
982 #[stable(feature = "rust1", since = "1.0.0")]
987 #[rustc_on_unimplemented(
988 message = "can't compare `{Self}` with `{Rhs}`",
989 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
991 #[rustc_diagnostic_item = "PartialOrd"]
992 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
993 /// This method returns an ordering between `self` and `other` values if one exists.
998 /// use std::cmp::Ordering;
1000 /// let result = 1.0.partial_cmp(&2.0);
1001 /// assert_eq!(result, Some(Ordering::Less));
1003 /// let result = 1.0.partial_cmp(&1.0);
1004 /// assert_eq!(result, Some(Ordering::Equal));
1006 /// let result = 2.0.partial_cmp(&1.0);
1007 /// assert_eq!(result, Some(Ordering::Greater));
1010 /// When comparison is impossible:
1013 /// let result = f64::NAN.partial_cmp(&1.0);
1014 /// assert_eq!(result, None);
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1020 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1025 /// let result = 1.0 < 2.0;
1026 /// assert_eq!(result, true);
1028 /// let result = 2.0 < 1.0;
1029 /// assert_eq!(result, false);
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 fn lt(&self, other: &Rhs) -> bool {
1035 matches!(self.partial_cmp(other), Some(Less))
1038 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1044 /// let result = 1.0 <= 2.0;
1045 /// assert_eq!(result, true);
1047 /// let result = 2.0 <= 2.0;
1048 /// assert_eq!(result, true);
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 fn le(&self, other: &Rhs) -> bool {
1054 // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`.
1055 // FIXME: The root cause was fixed upstream in LLVM with:
1056 // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775
1057 // Revert this workaround once support for LLVM 12 gets dropped.
1058 !matches!(self.partial_cmp(other), None | Some(Greater))
1061 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1066 /// let result = 1.0 > 2.0;
1067 /// assert_eq!(result, false);
1069 /// let result = 2.0 > 2.0;
1070 /// assert_eq!(result, false);
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 fn gt(&self, other: &Rhs) -> bool {
1076 matches!(self.partial_cmp(other), Some(Greater))
1079 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1085 /// let result = 2.0 >= 1.0;
1086 /// assert_eq!(result, true);
1088 /// let result = 2.0 >= 2.0;
1089 /// assert_eq!(result, true);
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 fn ge(&self, other: &Rhs) -> bool {
1095 matches!(self.partial_cmp(other), Some(Greater | Equal))
1099 /// Derive macro generating an impl of the trait `PartialOrd`.
1100 #[rustc_builtin_macro]
1101 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1102 #[allow_internal_unstable(core_intrinsics)]
1103 pub macro PartialOrd($item:item) {
1104 /* compiler built-in */
1107 /// Compares and returns the minimum of two values.
1109 /// Returns the first argument if the comparison determines them to be equal.
1111 /// Internally uses an alias to [`Ord::min`].
1118 /// assert_eq!(1, cmp::min(1, 2));
1119 /// assert_eq!(2, cmp::min(2, 2));
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1125 pub fn min<T: Ord>(v1: T, v2: T) -> T {
1129 /// Returns the minimum of two values with respect to the specified comparison function.
1131 /// Returns the first argument if the comparison determines them to be equal.
1138 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1139 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1143 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1144 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1145 match compare(&v1, &v2) {
1146 Ordering::Less | Ordering::Equal => v1,
1147 Ordering::Greater => v2,
1151 /// Returns the element that gives the minimum value from the specified function.
1153 /// Returns the first argument if the comparison determines them to be equal.
1160 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1161 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1165 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1166 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1167 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1170 /// Compares and returns the maximum of two values.
1172 /// Returns the second argument if the comparison determines them to be equal.
1174 /// Internally uses an alias to [`Ord::max`].
1181 /// assert_eq!(2, cmp::max(1, 2));
1182 /// assert_eq!(2, cmp::max(2, 2));
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1188 pub fn max<T: Ord>(v1: T, v2: T) -> T {
1192 /// Returns the maximum of two values with respect to the specified comparison function.
1194 /// Returns the second argument if the comparison determines them to be equal.
1201 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1202 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1206 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1207 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1208 match compare(&v1, &v2) {
1209 Ordering::Less | Ordering::Equal => v2,
1210 Ordering::Greater => v1,
1214 /// Returns the element that gives the maximum value from the specified function.
1216 /// Returns the second argument if the comparison determines them to be equal.
1223 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1224 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1228 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1229 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1230 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1233 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1235 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1236 use crate::hint::unreachable_unchecked;
1238 macro_rules! partial_eq_impl {
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 impl PartialEq for $t {
1243 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1245 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl PartialEq for () {
1253 fn eq(&self, _other: &()) -> bool {
1257 fn ne(&self, _other: &()) -> bool {
1263 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1266 macro_rules! eq_impl {
1268 #[stable(feature = "rust1", since = "1.0.0")]
1273 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1275 macro_rules! partial_ord_impl {
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl PartialOrd for $t {
1280 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1281 match (self <= other, self >= other) {
1282 (false, false) => None,
1283 (false, true) => Some(Greater),
1284 (true, false) => Some(Less),
1285 (true, true) => Some(Equal),
1289 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1291 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1293 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1295 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 impl PartialOrd for () {
1303 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1308 #[stable(feature = "rust1", since = "1.0.0")]
1309 impl PartialOrd for bool {
1311 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1312 Some(self.cmp(other))
1316 partial_ord_impl! { f32 f64 }
1318 macro_rules! ord_impl {
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 impl PartialOrd for $t {
1323 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1324 Some(self.cmp(other))
1327 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1329 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1331 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1333 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1336 #[stable(feature = "rust1", since = "1.0.0")]
1339 fn cmp(&self, other: &$t) -> Ordering {
1340 // The order here is important to generate more optimal assembly.
1341 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1342 if *self < *other { Less }
1343 else if *self == *other { Equal }
1350 #[stable(feature = "rust1", since = "1.0.0")]
1353 fn cmp(&self, _other: &()) -> Ordering {
1358 #[stable(feature = "rust1", since = "1.0.0")]
1361 fn cmp(&self, other: &bool) -> Ordering {
1362 // Casting to i8's and converting the difference to an Ordering generates
1363 // more optimal assembly.
1364 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1365 match (*self as i8) - (*other as i8) {
1369 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1370 _ => unsafe { unreachable_unchecked() },
1375 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1377 #[unstable(feature = "never_type", issue = "35121")]
1378 impl PartialEq for ! {
1379 fn eq(&self, _: &!) -> bool {
1384 #[unstable(feature = "never_type", issue = "35121")]
1387 #[unstable(feature = "never_type", issue = "35121")]
1388 impl PartialOrd for ! {
1389 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1394 #[unstable(feature = "never_type", issue = "35121")]
1396 fn cmp(&self, _: &!) -> Ordering {
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
1409 fn eq(&self, other: &&B) -> bool {
1410 PartialEq::eq(*self, *other)
1413 fn ne(&self, other: &&B) -> bool {
1414 PartialEq::ne(*self, *other)
1417 #[stable(feature = "rust1", since = "1.0.0")]
1418 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1423 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1424 PartialOrd::partial_cmp(*self, *other)
1427 fn lt(&self, other: &&B) -> bool {
1428 PartialOrd::lt(*self, *other)
1431 fn le(&self, other: &&B) -> bool {
1432 PartialOrd::le(*self, *other)
1435 fn gt(&self, other: &&B) -> bool {
1436 PartialOrd::gt(*self, *other)
1439 fn ge(&self, other: &&B) -> bool {
1440 PartialOrd::ge(*self, *other)
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<A: ?Sized> Ord for &A
1449 fn cmp(&self, other: &Self) -> Ordering {
1450 Ord::cmp(*self, *other)
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<A: ?Sized> Eq for &A where A: Eq {}
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1464 fn eq(&self, other: &&mut B) -> bool {
1465 PartialEq::eq(*self, *other)
1468 fn ne(&self, other: &&mut B) -> bool {
1469 PartialEq::ne(*self, *other)
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1478 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1479 PartialOrd::partial_cmp(*self, *other)
1482 fn lt(&self, other: &&mut B) -> bool {
1483 PartialOrd::lt(*self, *other)
1486 fn le(&self, other: &&mut B) -> bool {
1487 PartialOrd::le(*self, *other)
1490 fn gt(&self, other: &&mut B) -> bool {
1491 PartialOrd::gt(*self, *other)
1494 fn ge(&self, other: &&mut B) -> bool {
1495 PartialOrd::ge(*self, *other)
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<A: ?Sized> Ord for &mut A
1504 fn cmp(&self, other: &Self) -> Ordering {
1505 Ord::cmp(*self, *other)
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1517 fn eq(&self, other: &&mut B) -> bool {
1518 PartialEq::eq(*self, *other)
1521 fn ne(&self, other: &&mut B) -> bool {
1522 PartialEq::ne(*self, *other)
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1532 fn eq(&self, other: &&B) -> bool {
1533 PartialEq::eq(*self, *other)
1536 fn ne(&self, other: &&B) -> bool {
1537 PartialEq::ne(*self, *other)