1 //! Utilities for comparing and ordering values.
3 //! This module contains various tools for comparing and ordering 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 crate::const_closure::ConstFnMutClosure;
26 use crate::marker::Destruct;
28 use crate::marker::StructuralPartialEq;
30 use self::Ordering::*;
32 /// Trait for equality comparisons.
34 /// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
35 /// We use the easier-to-read infix notation in the remainder of this documentation.
37 /// This trait allows for partial equality, for types that do not have a full
38 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
39 /// so floating point types implement `PartialEq` but not [`trait@Eq`].
40 /// Formally speaking, when `Rhs == Self`, this trait corresponds to a [partial equivalence
41 /// relation](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
43 /// Implementations must ensure that `eq` and `ne` are consistent with each other:
45 /// - `a != b` if and only if `!(a == b)`.
47 /// The default implementation of `ne` provides this consistency and is almost
48 /// always sufficient. It should not be overridden without very good reason.
50 /// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
51 /// be consistent with `PartialEq` (see the documentation of those traits for the exact
52 /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
53 /// manually implementing others.
55 /// The equality relation `==` must satisfy the following conditions
56 /// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
58 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
59 /// implies `b == a`**; and
61 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
62 /// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
64 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
65 /// (transitive) impls are not forced to exist, but these requirements apply
66 /// whenever they do exist.
70 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
71 /// instances are equal if all fields are equal, and not equal if any fields
72 /// are not equal. When `derive`d on enums, two instances are equal if they
73 /// are the same variant and all fields are equal.
75 /// ## How can I implement `PartialEq`?
77 /// An example implementation for a domain in which two books are considered
78 /// the same book if their ISBN matches, even if the formats differ:
89 /// format: BookFormat,
92 /// impl PartialEq for Book {
93 /// fn eq(&self, other: &Self) -> bool {
94 /// self.isbn == other.isbn
98 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
99 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
100 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
102 /// assert!(b1 == b2);
103 /// assert!(b1 != b3);
106 /// ## How can I compare two different types?
108 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
109 /// For example, let's tweak our previous code a bit:
112 /// // The derive implements <BookFormat> == <BookFormat> comparisons
113 /// #[derive(PartialEq)]
114 /// enum BookFormat {
122 /// format: BookFormat,
125 /// // Implement <Book> == <BookFormat> comparisons
126 /// impl PartialEq<BookFormat> for Book {
127 /// fn eq(&self, other: &BookFormat) -> bool {
128 /// self.format == *other
132 /// // Implement <BookFormat> == <Book> comparisons
133 /// impl PartialEq<Book> for BookFormat {
134 /// fn eq(&self, other: &Book) -> bool {
135 /// *self == other.format
139 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
141 /// assert!(b1 == BookFormat::Paperback);
142 /// assert!(BookFormat::Ebook != b1);
145 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
146 /// we allow `BookFormat`s to be compared with `Book`s.
148 /// A comparison like the one above, which ignores some fields of the struct,
149 /// can be dangerous. It can easily lead to an unintended violation of the
150 /// requirements for a partial equivalence relation. For example, if we kept
151 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
152 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
153 /// via the manual implementation from the first example) then the result would
154 /// violate transitivity:
157 /// #[derive(PartialEq)]
158 /// enum BookFormat {
164 /// #[derive(PartialEq)]
167 /// format: BookFormat,
170 /// impl PartialEq<BookFormat> for Book {
171 /// fn eq(&self, other: &BookFormat) -> bool {
172 /// self.format == *other
176 /// impl PartialEq<Book> for BookFormat {
177 /// fn eq(&self, other: &Book) -> bool {
178 /// *self == other.format
183 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
184 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
186 /// assert!(b1 == BookFormat::Paperback);
187 /// assert!(BookFormat::Paperback == b2);
189 /// // The following should hold by transitivity but doesn't.
190 /// assert!(b1 == b2); // <-- PANICS
200 /// assert_eq!(x == y, false);
201 /// assert_eq!(x.eq(&y), false);
204 /// [`eq`]: PartialEq::eq
205 /// [`ne`]: PartialEq::ne
207 #[stable(feature = "rust1", since = "1.0.0")]
210 #[rustc_on_unimplemented(
211 message = "can't compare `{Self}` with `{Rhs}`",
212 label = "no implementation for `{Self} == {Rhs}`",
216 #[rustc_diagnostic_item = "PartialEq"]
217 pub trait PartialEq<Rhs: ?Sized = Self> {
218 /// This method tests for `self` and `other` values to be equal, and is used
221 #[stable(feature = "rust1", since = "1.0.0")]
222 fn eq(&self, other: &Rhs) -> bool;
224 /// This method tests for `!=`. The default implementation is almost always
225 /// sufficient, and should not be overridden without very good reason.
228 #[stable(feature = "rust1", since = "1.0.0")]
229 fn ne(&self, other: &Rhs) -> bool {
234 /// Derive macro generating an impl of the trait `PartialEq`.
235 #[rustc_builtin_macro]
236 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
237 #[allow_internal_unstable(core_intrinsics, structural_match)]
238 pub macro PartialEq($item:item) {
239 /* compiler built-in */
242 /// Trait for equality comparisons which are [equivalence relations](
243 /// https://en.wikipedia.org/wiki/Equivalence_relation).
245 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
246 /// be (for all `a`, `b` and `c`):
248 /// - reflexive: `a == a`;
249 /// - symmetric: `a == b` implies `b == a`; and
250 /// - transitive: `a == b` and `b == c` implies `a == c`.
252 /// This property cannot be checked by the compiler, and therefore `Eq` implies
253 /// [`PartialEq`], and has no extra methods.
257 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
258 /// no extra methods, it is only informing the compiler that this is an
259 /// equivalence relation rather than a partial equivalence relation. Note that
260 /// the `derive` strategy requires all fields are `Eq`, which isn't
263 /// ## How can I implement `Eq`?
265 /// If you cannot use the `derive` strategy, specify that your type implements
266 /// `Eq`, which has no methods:
269 /// enum BookFormat { Paperback, Hardback, Ebook }
272 /// format: BookFormat,
274 /// impl PartialEq for Book {
275 /// fn eq(&self, other: &Self) -> bool {
276 /// self.isbn == other.isbn
279 /// impl Eq for Book {}
283 #[stable(feature = "rust1", since = "1.0.0")]
284 #[rustc_diagnostic_item = "Eq"]
285 pub trait Eq: PartialEq<Self> {
286 // this method is used solely by #[deriving] to assert
287 // that every component of a type implements #[deriving]
288 // itself, the current deriving infrastructure means doing this
289 // assertion without using a method on this trait is nearly
292 // This should never be implemented by hand.
294 #[no_coverage] // rust-lang/rust#84605
296 #[stable(feature = "rust1", since = "1.0.0")]
297 fn assert_receiver_is_total_eq(&self) {}
300 /// Derive macro generating an impl of the trait `Eq`.
301 #[rustc_builtin_macro]
302 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
303 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
304 pub macro Eq($item:item) {
305 /* compiler built-in */
308 // FIXME: this struct is used solely by #[derive] to
309 // assert that every component of a type implements Eq.
311 // This struct should never appear in user code.
313 #[allow(missing_debug_implementations)]
314 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
315 pub struct AssertParamIsEq<T: Eq + ?Sized> {
316 _field: crate::marker::PhantomData<T>,
319 /// An `Ordering` is the result of a comparison between two values.
324 /// use std::cmp::Ordering;
326 /// let result = 1.cmp(&2);
327 /// assert_eq!(Ordering::Less, result);
329 /// let result = 1.cmp(&1);
330 /// assert_eq!(Ordering::Equal, result);
332 /// let result = 2.cmp(&1);
333 /// assert_eq!(Ordering::Greater, result);
335 #[derive(Clone, Copy, Eq, Debug, Hash)]
336 #[cfg_attr(not(bootstrap), derive_const(PartialOrd, Ord, PartialEq))]
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 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
607 impl<T: ~const PartialOrd> const 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"]
766 pub trait Ord: Eq + PartialOrd<Self> {
767 /// This method returns an [`Ordering`] between `self` and `other`.
769 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
770 /// `self <operator> other` if true.
775 /// use std::cmp::Ordering;
777 /// assert_eq!(5.cmp(&10), Ordering::Less);
778 /// assert_eq!(10.cmp(&5), Ordering::Greater);
779 /// assert_eq!(5.cmp(&5), Ordering::Equal);
782 #[stable(feature = "rust1", since = "1.0.0")]
783 fn cmp(&self, other: &Self) -> Ordering;
785 /// Compares and returns the maximum of two values.
787 /// Returns the second argument if the comparison determines them to be equal.
792 /// assert_eq!(2, 1.max(2));
793 /// assert_eq!(2, 2.max(2));
795 #[stable(feature = "ord_max_min", since = "1.21.0")]
798 fn max(self, other: Self) -> Self
801 Self: ~const Destruct,
803 // HACK(fee1-dead): go back to using `self.max_by(other, Ord::cmp)`
804 // when trait methods are allowed to be used when a const closure is
806 match self.cmp(&other) {
807 Ordering::Less | Ordering::Equal => other,
808 Ordering::Greater => self,
812 /// Compares and returns the minimum of two values.
814 /// Returns the first argument if the comparison determines them to be equal.
819 /// assert_eq!(1, 1.min(2));
820 /// assert_eq!(2, 2.min(2));
822 #[stable(feature = "ord_max_min", since = "1.21.0")]
825 fn min(self, other: Self) -> Self
828 Self: ~const Destruct,
830 // HACK(fee1-dead): go back to using `self.min_by(other, Ord::cmp)`
831 // when trait methods are allowed to be used when a const closure is
833 match self.cmp(&other) {
834 Ordering::Less | Ordering::Equal => self,
835 Ordering::Greater => other,
839 /// Restrict a value to a certain interval.
841 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
842 /// less than `min`. Otherwise this returns `self`.
846 /// Panics if `min > max`.
851 /// assert!((-3).clamp(-2, 1) == -2);
852 /// assert!(0.clamp(-2, 1) == 0);
853 /// assert!(2.clamp(-2, 1) == 1);
856 #[stable(feature = "clamp", since = "1.50.0")]
857 fn clamp(self, min: Self, max: Self) -> Self
860 Self: ~const Destruct,
861 Self: ~const PartialOrd,
866 } else if self > max {
874 /// Derive macro generating an impl of the trait `Ord`.
875 #[rustc_builtin_macro]
876 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
877 #[allow_internal_unstable(core_intrinsics)]
878 pub macro Ord($item:item) {
879 /* compiler built-in */
882 #[stable(feature = "rust1", since = "1.0.0")]
884 impl StructuralPartialEq for Ordering {}
886 #[stable(feature = "rust1", since = "1.0.0")]
887 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
889 impl const PartialEq for Ordering {
891 fn eq(&self, other: &Self) -> bool {
892 (*self as i32).eq(&(*other as i32))
896 #[stable(feature = "rust1", since = "1.0.0")]
897 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
899 impl const Ord for Ordering {
901 fn cmp(&self, other: &Ordering) -> Ordering {
902 (*self as i32).cmp(&(*other as i32))
906 #[stable(feature = "rust1", since = "1.0.0")]
907 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
909 impl const PartialOrd for Ordering {
911 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
912 (*self as i32).partial_cmp(&(*other as i32))
916 /// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
918 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
919 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
921 /// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
922 /// The following conditions must hold:
924 /// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
925 /// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
926 /// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
927 /// 4. `a <= b` if and only if `a < b || a == b`
928 /// 5. `a >= b` if and only if `a > b || a == b`
929 /// 6. `a != b` if and only if `!(a == b)`.
931 /// Conditions 2–5 above are ensured by the default implementation.
932 /// Condition 6 is already ensured by [`PartialEq`].
934 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
935 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
936 /// easy to accidentally make them disagree by deriving some of the traits and manually
937 /// implementing others.
939 /// The comparison must satisfy, for all `a`, `b` and `c`:
941 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
942 /// - duality: `a < b` if and only if `b > a`.
944 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
945 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
950 /// The following corollaries follow from the above requirements:
952 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
953 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
954 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
958 /// This trait can be used with `#[derive]`.
960 /// When `derive`d on structs, it will produce a
961 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
962 /// based on the top-to-bottom declaration order of the struct's members.
964 /// When `derive`d on enums, variants are ordered by their discriminants.
965 /// By default, the discriminant is smallest for variants at the top, and
966 /// largest for variants at the bottom. Here's an example:
969 /// #[derive(PartialEq, PartialOrd)]
975 /// assert!(E::Top < E::Bottom);
978 /// However, manually setting the discriminants can override this default
982 /// #[derive(PartialEq, PartialOrd)]
988 /// assert!(E::Bottom < E::Top);
991 /// ## How can I implement `PartialOrd`?
993 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
994 /// generated from default implementations.
996 /// However it remains possible to implement the others separately for types which do not have a
997 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
998 /// false` (cf. IEEE 754-2008 section 5.11).
1000 /// `PartialOrd` requires your type to be [`PartialEq`].
1002 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
1005 /// use std::cmp::Ordering;
1014 /// impl PartialOrd for Person {
1015 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1016 /// Some(self.cmp(other))
1020 /// impl Ord for Person {
1021 /// fn cmp(&self, other: &Self) -> Ordering {
1022 /// self.height.cmp(&other.height)
1026 /// impl PartialEq for Person {
1027 /// fn eq(&self, other: &Self) -> bool {
1028 /// self.height == other.height
1033 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
1034 /// is an example of `Person` types who have a floating-point `height` field that
1035 /// is the only field to be used for sorting:
1038 /// use std::cmp::Ordering;
1046 /// impl PartialOrd for Person {
1047 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1048 /// self.height.partial_cmp(&other.height)
1052 /// impl PartialEq for Person {
1053 /// fn eq(&self, other: &Self) -> bool {
1054 /// self.height == other.height
1065 /// assert_eq!(x < y, true);
1066 /// assert_eq!(x.lt(&y), true);
1069 /// [`partial_cmp`]: PartialOrd::partial_cmp
1070 /// [`cmp`]: Ord::cmp
1071 #[lang = "partial_ord"]
1072 #[stable(feature = "rust1", since = "1.0.0")]
1075 #[doc(alias = "<=")]
1076 #[doc(alias = ">=")]
1077 #[rustc_on_unimplemented(
1078 message = "can't compare `{Self}` with `{Rhs}`",
1079 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1083 #[rustc_diagnostic_item = "PartialOrd"]
1084 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
1085 /// This method returns an ordering between `self` and `other` values if one exists.
1090 /// use std::cmp::Ordering;
1092 /// let result = 1.0.partial_cmp(&2.0);
1093 /// assert_eq!(result, Some(Ordering::Less));
1095 /// let result = 1.0.partial_cmp(&1.0);
1096 /// assert_eq!(result, Some(Ordering::Equal));
1098 /// let result = 2.0.partial_cmp(&1.0);
1099 /// assert_eq!(result, Some(Ordering::Greater));
1102 /// When comparison is impossible:
1105 /// let result = f64::NAN.partial_cmp(&1.0);
1106 /// assert_eq!(result, None);
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1112 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1117 /// let result = 1.0 < 2.0;
1118 /// assert_eq!(result, true);
1120 /// let result = 2.0 < 1.0;
1121 /// assert_eq!(result, false);
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 fn lt(&self, other: &Rhs) -> bool {
1127 matches!(self.partial_cmp(other), Some(Less))
1130 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1136 /// let result = 1.0 <= 2.0;
1137 /// assert_eq!(result, true);
1139 /// let result = 2.0 <= 2.0;
1140 /// assert_eq!(result, true);
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 fn le(&self, other: &Rhs) -> bool {
1146 matches!(self.partial_cmp(other), Some(Less | Equal))
1149 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1154 /// let result = 1.0 > 2.0;
1155 /// assert_eq!(result, false);
1157 /// let result = 2.0 > 2.0;
1158 /// assert_eq!(result, false);
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 fn gt(&self, other: &Rhs) -> bool {
1164 matches!(self.partial_cmp(other), Some(Greater))
1167 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1173 /// let result = 2.0 >= 1.0;
1174 /// assert_eq!(result, true);
1176 /// let result = 2.0 >= 2.0;
1177 /// assert_eq!(result, true);
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 fn ge(&self, other: &Rhs) -> bool {
1183 matches!(self.partial_cmp(other), Some(Greater | Equal))
1187 /// Derive macro generating an impl of the trait `PartialOrd`.
1188 #[rustc_builtin_macro]
1189 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1190 #[allow_internal_unstable(core_intrinsics)]
1191 pub macro PartialOrd($item:item) {
1192 /* compiler built-in */
1195 /// Compares and returns the minimum of two values.
1197 /// Returns the first argument if the comparison determines them to be equal.
1199 /// Internally uses an alias to [`Ord::min`].
1206 /// assert_eq!(1, cmp::min(1, 2));
1207 /// assert_eq!(2, cmp::min(2, 2));
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1213 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1214 pub const fn min<T: ~const Ord + ~const Destruct>(v1: T, v2: T) -> T {
1218 /// Returns the minimum of two values with respect to the specified comparison function.
1220 /// Returns the first argument if the comparison determines them to be equal.
1227 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1228 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1232 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1233 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1234 pub const fn min_by<T, F: ~const FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T
1239 match compare(&v1, &v2) {
1240 Ordering::Less | Ordering::Equal => v1,
1241 Ordering::Greater => v2,
1245 /// Returns the element that gives the minimum value from the specified function.
1247 /// Returns the first argument if the comparison determines them to be equal.
1254 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1255 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1259 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1260 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1261 pub const fn min_by_key<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(v1: T, v2: T, mut f: F) -> T
1267 const fn imp<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(
1277 min_by(v1, v2, ConstFnMutClosure::new(&mut f, imp))
1280 /// Compares and returns the maximum of two values.
1282 /// Returns the second argument if the comparison determines them to be equal.
1284 /// Internally uses an alias to [`Ord::max`].
1291 /// assert_eq!(2, cmp::max(1, 2));
1292 /// assert_eq!(2, cmp::max(2, 2));
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1298 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1299 pub const fn max<T: ~const Ord + ~const Destruct>(v1: T, v2: T) -> T {
1303 /// Returns the maximum of two values with respect to the specified comparison function.
1305 /// Returns the second argument if the comparison determines them to be equal.
1312 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1313 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1317 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1318 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1319 pub const fn max_by<T, F: ~const FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T
1324 match compare(&v1, &v2) {
1325 Ordering::Less | Ordering::Equal => v2,
1326 Ordering::Greater => v1,
1330 /// Returns the element that gives the maximum value from the specified function.
1332 /// Returns the second argument if the comparison determines them to be equal.
1339 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1340 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1344 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1345 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1346 pub const fn max_by_key<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(v1: T, v2: T, mut f: F) -> T
1352 const fn imp<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(
1362 max_by(v1, v2, ConstFnMutClosure::new(&mut f, imp))
1365 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1367 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1368 use crate::hint::unreachable_unchecked;
1370 macro_rules! partial_eq_impl {
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1374 impl const PartialEq for $t {
1376 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1378 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1385 impl const PartialEq for () {
1387 fn eq(&self, _other: &()) -> bool {
1391 fn ne(&self, _other: &()) -> bool {
1397 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1400 macro_rules! eq_impl {
1402 #[stable(feature = "rust1", since = "1.0.0")]
1407 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1409 macro_rules! partial_ord_impl {
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1413 impl const PartialOrd for $t {
1415 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1416 match (*self <= *other, *self >= *other) {
1417 (false, false) => None,
1418 (false, true) => Some(Greater),
1419 (true, false) => Some(Less),
1420 (true, true) => Some(Equal),
1424 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1426 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1428 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1430 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1437 impl const PartialOrd for () {
1439 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1446 impl const PartialOrd for bool {
1448 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1449 Some(self.cmp(other))
1453 partial_ord_impl! { f32 f64 }
1455 macro_rules! ord_impl {
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1459 impl const PartialOrd for $t {
1461 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1462 Some(self.cmp(other))
1465 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1467 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1469 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1471 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1476 impl const Ord for $t {
1478 fn cmp(&self, other: &$t) -> Ordering {
1479 // The order here is important to generate more optimal assembly.
1480 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1481 if *self < *other { Less }
1482 else if *self == *other { Equal }
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1491 impl const Ord for () {
1493 fn cmp(&self, _other: &()) -> Ordering {
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1500 impl const Ord for bool {
1502 fn cmp(&self, other: &bool) -> Ordering {
1503 // Casting to i8's and converting the difference to an Ordering generates
1504 // more optimal assembly.
1505 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1506 match (*self as i8) - (*other as i8) {
1510 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1511 _ => unsafe { unreachable_unchecked() },
1516 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1518 #[unstable(feature = "never_type", issue = "35121")]
1519 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1520 impl const PartialEq for ! {
1521 fn eq(&self, _: &!) -> bool {
1526 #[unstable(feature = "never_type", issue = "35121")]
1529 #[unstable(feature = "never_type", issue = "35121")]
1530 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1531 impl const PartialOrd for ! {
1532 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1537 #[unstable(feature = "never_type", issue = "35121")]
1538 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1539 impl const Ord for ! {
1540 fn cmp(&self, _: &!) -> Ordering {
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1549 impl<A: ?Sized, B: ?Sized> const PartialEq<&B> for &A
1551 A: ~const PartialEq<B>,
1554 fn eq(&self, other: &&B) -> bool {
1555 PartialEq::eq(*self, *other)
1558 fn ne(&self, other: &&B) -> bool {
1559 PartialEq::ne(*self, *other)
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1568 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1569 PartialOrd::partial_cmp(*self, *other)
1572 fn lt(&self, other: &&B) -> bool {
1573 PartialOrd::lt(*self, *other)
1576 fn le(&self, other: &&B) -> bool {
1577 PartialOrd::le(*self, *other)
1580 fn gt(&self, other: &&B) -> bool {
1581 PartialOrd::gt(*self, *other)
1584 fn ge(&self, other: &&B) -> bool {
1585 PartialOrd::ge(*self, *other)
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 impl<A: ?Sized> Ord for &A
1594 fn cmp(&self, other: &Self) -> Ordering {
1595 Ord::cmp(*self, *other)
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<A: ?Sized> Eq for &A where A: Eq {}
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1609 fn eq(&self, other: &&mut B) -> bool {
1610 PartialEq::eq(*self, *other)
1613 fn ne(&self, other: &&mut B) -> bool {
1614 PartialEq::ne(*self, *other)
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1623 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1624 PartialOrd::partial_cmp(*self, *other)
1627 fn lt(&self, other: &&mut B) -> bool {
1628 PartialOrd::lt(*self, *other)
1631 fn le(&self, other: &&mut B) -> bool {
1632 PartialOrd::le(*self, *other)
1635 fn gt(&self, other: &&mut B) -> bool {
1636 PartialOrd::gt(*self, *other)
1639 fn ge(&self, other: &&mut B) -> bool {
1640 PartialOrd::ge(*self, *other)
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<A: ?Sized> Ord for &mut A
1649 fn cmp(&self, other: &Self) -> Ordering {
1650 Ord::cmp(*self, *other)
1653 #[stable(feature = "rust1", since = "1.0.0")]
1654 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1662 fn eq(&self, other: &&mut B) -> bool {
1663 PartialEq::eq(*self, *other)
1666 fn ne(&self, other: &&mut B) -> bool {
1667 PartialEq::ne(*self, *other)
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1677 fn eq(&self, other: &&B) -> bool {
1678 PartialEq::eq(*self, *other)
1681 fn ne(&self, other: &&B) -> bool {
1682 PartialEq::ne(*self, *other)