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 crate::marker::Destruct;
27 use self::Ordering::*;
29 /// Trait for equality comparisons which are [partial equivalence
30 /// relations](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
32 /// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
33 /// We use the easier-to-read infix notation in the remainder of this documentation.
35 /// This trait allows for partial equality, for types that do not have a full
36 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
37 /// so floating point types implement `PartialEq` but not [`trait@Eq`].
39 /// Implementations must ensure that `eq` and `ne` are consistent with each other:
41 /// - `a != b` if and only if `!(a == b)`
42 /// (ensured by the default implementation).
44 /// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
45 /// be consistent with `PartialEq` (see the documentation of those traits for the exact
46 /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
47 /// manually implementing others.
49 /// The equality relation `==` must satisfy the following conditions
50 /// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
52 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
53 /// implies `b == a`**; and
55 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
56 /// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
58 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
59 /// (transitive) impls are not forced to exist, but these requirements apply
60 /// whenever they do exist.
64 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
65 /// instances are equal if all fields are equal, and not equal if any fields
66 /// are not equal. When `derive`d on enums, two instances are equal if they
67 /// are the same variant and all fields are equal.
69 /// ## How can I implement `PartialEq`?
71 /// An example implementation for a domain in which two books are considered
72 /// the same book if their ISBN matches, even if the formats differ:
83 /// format: BookFormat,
86 /// impl PartialEq for Book {
87 /// fn eq(&self, other: &Self) -> bool {
88 /// self.isbn == other.isbn
92 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
93 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
94 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
96 /// assert!(b1 == b2);
97 /// assert!(b1 != b3);
100 /// ## How can I compare two different types?
102 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
103 /// For example, let's tweak our previous code a bit:
106 /// // The derive implements <BookFormat> == <BookFormat> comparisons
107 /// #[derive(PartialEq)]
108 /// enum BookFormat {
116 /// format: BookFormat,
119 /// // Implement <Book> == <BookFormat> comparisons
120 /// impl PartialEq<BookFormat> for Book {
121 /// fn eq(&self, other: &BookFormat) -> bool {
122 /// self.format == *other
126 /// // Implement <BookFormat> == <Book> comparisons
127 /// impl PartialEq<Book> for BookFormat {
128 /// fn eq(&self, other: &Book) -> bool {
129 /// *self == other.format
133 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
135 /// assert!(b1 == BookFormat::Paperback);
136 /// assert!(BookFormat::Ebook != b1);
139 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
140 /// we allow `BookFormat`s to be compared with `Book`s.
142 /// A comparison like the one above, which ignores some fields of the struct,
143 /// can be dangerous. It can easily lead to an unintended violation of the
144 /// requirements for a partial equivalence relation. For example, if we kept
145 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
146 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
147 /// via the manual implementation from the first example) then the result would
148 /// violate transitivity:
151 /// #[derive(PartialEq)]
152 /// enum BookFormat {
158 /// #[derive(PartialEq)]
161 /// format: BookFormat,
164 /// impl PartialEq<BookFormat> for Book {
165 /// fn eq(&self, other: &BookFormat) -> bool {
166 /// self.format == *other
170 /// impl PartialEq<Book> for BookFormat {
171 /// fn eq(&self, other: &Book) -> bool {
172 /// *self == other.format
177 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
178 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
180 /// assert!(b1 == BookFormat::Paperback);
181 /// assert!(BookFormat::Paperback == b2);
183 /// // The following should hold by transitivity but doesn't.
184 /// assert!(b1 == b2); // <-- PANICS
194 /// assert_eq!(x == y, false);
195 /// assert_eq!(x.eq(&y), false);
198 /// [`eq`]: PartialEq::eq
199 /// [`ne`]: PartialEq::ne
201 #[stable(feature = "rust1", since = "1.0.0")]
206 rustc_on_unimplemented(
207 message = "can't compare `{Self}` with `{Rhs}`",
208 label = "no implementation for `{Self} == {Rhs}`"
213 rustc_on_unimplemented(
214 message = "can't compare `{Self}` with `{Rhs}`",
215 label = "no implementation for `{Self} == {Rhs}`",
220 #[rustc_diagnostic_item = "PartialEq"]
221 pub trait PartialEq<Rhs: ?Sized = Self> {
222 /// This method tests for `self` and `other` values to be equal, and is used
225 #[stable(feature = "rust1", since = "1.0.0")]
226 fn eq(&self, other: &Rhs) -> bool;
228 /// This method tests for `!=`.
231 #[stable(feature = "rust1", since = "1.0.0")]
232 fn ne(&self, other: &Rhs) -> bool {
237 /// Derive macro generating an impl of the trait `PartialEq`.
238 #[rustc_builtin_macro]
239 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
240 #[allow_internal_unstable(core_intrinsics, structural_match)]
241 pub macro PartialEq($item:item) {
242 /* compiler built-in */
245 /// Trait for equality comparisons which are [equivalence relations](
246 /// https://en.wikipedia.org/wiki/Equivalence_relation).
248 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
249 /// be (for all `a`, `b` and `c`):
251 /// - reflexive: `a == a`;
252 /// - symmetric: `a == b` implies `b == a`; and
253 /// - transitive: `a == b` and `b == c` implies `a == c`.
255 /// This property cannot be checked by the compiler, and therefore `Eq` implies
256 /// [`PartialEq`], and has no extra methods.
260 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
261 /// no extra methods, it is only informing the compiler that this is an
262 /// equivalence relation rather than a partial equivalence relation. Note that
263 /// the `derive` strategy requires all fields are `Eq`, which isn't
266 /// ## How can I implement `Eq`?
268 /// If you cannot use the `derive` strategy, specify that your type implements
269 /// `Eq`, which has no methods:
272 /// enum BookFormat { Paperback, Hardback, Ebook }
275 /// format: BookFormat,
277 /// impl PartialEq for Book {
278 /// fn eq(&self, other: &Self) -> bool {
279 /// self.isbn == other.isbn
282 /// impl Eq for Book {}
286 #[stable(feature = "rust1", since = "1.0.0")]
287 #[rustc_diagnostic_item = "Eq"]
288 pub trait Eq: PartialEq<Self> {
289 // this method is used solely by #[deriving] to assert
290 // that every component of a type implements #[deriving]
291 // itself, the current deriving infrastructure means doing this
292 // assertion without using a method on this trait is nearly
295 // This should never be implemented by hand.
297 #[no_coverage] // rust-lang/rust#84605
299 #[stable(feature = "rust1", since = "1.0.0")]
300 fn assert_receiver_is_total_eq(&self) {}
303 /// Derive macro generating an impl of the trait `Eq`.
304 #[rustc_builtin_macro]
305 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
306 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
307 pub macro Eq($item:item) {
308 /* compiler built-in */
311 // FIXME: this struct is used solely by #[derive] to
312 // assert that every component of a type implements Eq.
314 // This struct should never appear in user code.
316 #[allow(missing_debug_implementations)]
317 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
318 pub struct AssertParamIsEq<T: Eq + ?Sized> {
319 _field: crate::marker::PhantomData<T>,
322 /// An `Ordering` is the result of a comparison between two values.
327 /// use std::cmp::Ordering;
329 /// let result = 1.cmp(&2);
330 /// assert_eq!(Ordering::Less, result);
332 /// let result = 1.cmp(&1);
333 /// assert_eq!(Ordering::Equal, result);
335 /// let result = 2.cmp(&1);
336 /// assert_eq!(Ordering::Greater, result);
338 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
339 #[stable(feature = "rust1", since = "1.0.0")]
342 /// An ordering where a compared value is less than another.
343 #[stable(feature = "rust1", since = "1.0.0")]
345 /// An ordering where a compared value is equal to another.
346 #[stable(feature = "rust1", since = "1.0.0")]
348 /// An ordering where a compared value is greater than another.
349 #[stable(feature = "rust1", since = "1.0.0")]
354 /// Returns `true` if the ordering is the `Equal` variant.
359 /// use std::cmp::Ordering;
361 /// assert_eq!(Ordering::Less.is_eq(), false);
362 /// assert_eq!(Ordering::Equal.is_eq(), true);
363 /// assert_eq!(Ordering::Greater.is_eq(), false);
367 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
368 #[stable(feature = "ordering_helpers", since = "1.53.0")]
369 pub const fn is_eq(self) -> bool {
370 matches!(self, Equal)
373 /// Returns `true` if the ordering is not the `Equal` variant.
378 /// use std::cmp::Ordering;
380 /// assert_eq!(Ordering::Less.is_ne(), true);
381 /// assert_eq!(Ordering::Equal.is_ne(), false);
382 /// assert_eq!(Ordering::Greater.is_ne(), true);
386 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
387 #[stable(feature = "ordering_helpers", since = "1.53.0")]
388 pub const fn is_ne(self) -> bool {
389 !matches!(self, Equal)
392 /// Returns `true` if the ordering is the `Less` variant.
397 /// use std::cmp::Ordering;
399 /// assert_eq!(Ordering::Less.is_lt(), true);
400 /// assert_eq!(Ordering::Equal.is_lt(), false);
401 /// assert_eq!(Ordering::Greater.is_lt(), false);
405 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
406 #[stable(feature = "ordering_helpers", since = "1.53.0")]
407 pub const fn is_lt(self) -> bool {
411 /// Returns `true` if the ordering is the `Greater` variant.
416 /// use std::cmp::Ordering;
418 /// assert_eq!(Ordering::Less.is_gt(), false);
419 /// assert_eq!(Ordering::Equal.is_gt(), false);
420 /// assert_eq!(Ordering::Greater.is_gt(), true);
424 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
425 #[stable(feature = "ordering_helpers", since = "1.53.0")]
426 pub const fn is_gt(self) -> bool {
427 matches!(self, Greater)
430 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
435 /// use std::cmp::Ordering;
437 /// assert_eq!(Ordering::Less.is_le(), true);
438 /// assert_eq!(Ordering::Equal.is_le(), true);
439 /// assert_eq!(Ordering::Greater.is_le(), false);
443 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
444 #[stable(feature = "ordering_helpers", since = "1.53.0")]
445 pub const fn is_le(self) -> bool {
446 !matches!(self, Greater)
449 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
454 /// use std::cmp::Ordering;
456 /// assert_eq!(Ordering::Less.is_ge(), false);
457 /// assert_eq!(Ordering::Equal.is_ge(), true);
458 /// assert_eq!(Ordering::Greater.is_ge(), true);
462 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
463 #[stable(feature = "ordering_helpers", since = "1.53.0")]
464 pub const fn is_ge(self) -> bool {
465 !matches!(self, Less)
468 /// Reverses the `Ordering`.
470 /// * `Less` becomes `Greater`.
471 /// * `Greater` becomes `Less`.
472 /// * `Equal` becomes `Equal`.
479 /// use std::cmp::Ordering;
481 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
482 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
483 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
486 /// This method can be used to reverse a comparison:
489 /// let data: &mut [_] = &mut [2, 10, 5, 8];
491 /// // sort the array from largest to smallest.
492 /// data.sort_by(|a, b| a.cmp(b).reverse());
494 /// let b: &mut [_] = &mut [10, 8, 5, 2];
495 /// assert!(data == b);
499 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub const fn reverse(self) -> Ordering {
509 /// Chains two orderings.
511 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
516 /// use std::cmp::Ordering;
518 /// let result = Ordering::Equal.then(Ordering::Less);
519 /// assert_eq!(result, Ordering::Less);
521 /// let result = Ordering::Less.then(Ordering::Equal);
522 /// assert_eq!(result, Ordering::Less);
524 /// let result = Ordering::Less.then(Ordering::Greater);
525 /// assert_eq!(result, Ordering::Less);
527 /// let result = Ordering::Equal.then(Ordering::Equal);
528 /// assert_eq!(result, Ordering::Equal);
530 /// let x: (i64, i64, i64) = (1, 2, 7);
531 /// let y: (i64, i64, i64) = (1, 5, 3);
532 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
534 /// assert_eq!(result, Ordering::Less);
538 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
539 #[stable(feature = "ordering_chaining", since = "1.17.0")]
540 pub const fn then(self, other: Ordering) -> Ordering {
547 /// Chains the ordering with the given function.
549 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
555 /// use std::cmp::Ordering;
557 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
558 /// assert_eq!(result, Ordering::Less);
560 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
561 /// assert_eq!(result, Ordering::Less);
563 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
564 /// assert_eq!(result, Ordering::Less);
566 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
567 /// assert_eq!(result, Ordering::Equal);
569 /// let x: (i64, i64, i64) = (1, 2, 7);
570 /// let y: (i64, i64, i64) = (1, 5, 3);
571 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
573 /// assert_eq!(result, Ordering::Less);
577 #[stable(feature = "ordering_chaining", since = "1.17.0")]
578 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
586 /// A helper struct for reverse ordering.
588 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
589 /// can be used to reverse order a part of a key.
591 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
596 /// use std::cmp::Reverse;
598 /// let mut v = vec![1, 2, 3, 4, 5, 6];
599 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
600 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
602 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
603 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
605 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
607 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
608 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
609 impl<T: ~const PartialOrd> const PartialOrd for Reverse<T> {
611 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
612 other.0.partial_cmp(&self.0)
616 fn lt(&self, other: &Self) -> bool {
620 fn le(&self, other: &Self) -> bool {
624 fn gt(&self, other: &Self) -> bool {
628 fn ge(&self, other: &Self) -> bool {
633 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
634 impl<T: Ord> Ord for Reverse<T> {
636 fn cmp(&self, other: &Reverse<T>) -> Ordering {
641 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
642 impl<T: Clone> Clone for Reverse<T> {
644 fn clone(&self) -> Reverse<T> {
645 Reverse(self.0.clone())
649 fn clone_from(&mut self, other: &Self) {
650 self.0.clone_from(&other.0)
654 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
656 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
657 /// `max`, `min`, and `clamp` are consistent with `cmp`:
659 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
660 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
661 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
662 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
663 /// (ensured by the default implementation).
665 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
666 /// deriving some of the traits and manually implementing others.
670 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
671 /// This means that for all `a`, `b` and `c`:
673 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
674 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
678 /// This trait can be used with `#[derive]`.
680 /// When `derive`d on structs, it will produce a
681 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
682 /// based on the top-to-bottom declaration order of the struct's members.
684 /// When `derive`d on enums, variants are ordered by their discriminants.
685 /// By default, the discriminant is smallest for variants at the top, and
686 /// largest for variants at the bottom. Here's an example:
689 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
695 /// assert!(E::Top < E::Bottom);
698 /// However, manually setting the discriminants can override this default
702 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
708 /// assert!(E::Bottom < E::Top);
711 /// ## Lexicographical comparison
713 /// Lexicographical comparison is an operation with the following properties:
714 /// - Two sequences are compared element by element.
715 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
716 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
717 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
718 /// - An empty sequence is lexicographically less than any non-empty sequence.
719 /// - Two empty sequences are lexicographically equal.
721 /// ## How can I implement `Ord`?
723 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
725 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
726 /// [`cmp`] on your type's fields.
728 /// Here's an example where you want to sort people by height only, disregarding `id`
732 /// use std::cmp::Ordering;
741 /// impl Ord for Person {
742 /// fn cmp(&self, other: &Self) -> Ordering {
743 /// self.height.cmp(&other.height)
747 /// impl PartialOrd for Person {
748 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
749 /// Some(self.cmp(other))
753 /// impl PartialEq for Person {
754 /// fn eq(&self, other: &Self) -> bool {
755 /// self.height == other.height
760 /// [`cmp`]: Ord::cmp
765 #[stable(feature = "rust1", since = "1.0.0")]
766 #[rustc_diagnostic_item = "Ord"]
768 pub trait Ord: Eq + PartialOrd<Self> {
769 /// This method returns an [`Ordering`] between `self` and `other`.
771 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
772 /// `self <operator> other` if true.
777 /// use std::cmp::Ordering;
779 /// assert_eq!(5.cmp(&10), Ordering::Less);
780 /// assert_eq!(10.cmp(&5), Ordering::Greater);
781 /// assert_eq!(5.cmp(&5), Ordering::Equal);
784 #[stable(feature = "rust1", since = "1.0.0")]
785 fn cmp(&self, other: &Self) -> Ordering;
787 /// Compares and returns the maximum of two values.
789 /// Returns the second argument if the comparison determines them to be equal.
794 /// assert_eq!(2, 1.max(2));
795 /// assert_eq!(2, 2.max(2));
797 #[stable(feature = "ord_max_min", since = "1.21.0")]
800 fn max(self, other: Self) -> Self
803 Self: ~const Destruct,
805 // HACK(fee1-dead): go back to using `self.max_by(other, Ord::cmp)`
806 // when trait methods are allowed to be used when a const closure is
808 match self.cmp(&other) {
809 Ordering::Less | Ordering::Equal => other,
810 Ordering::Greater => self,
814 /// Compares and returns the minimum of two values.
816 /// Returns the first argument if the comparison determines them to be equal.
821 /// assert_eq!(1, 1.min(2));
822 /// assert_eq!(2, 2.min(2));
824 #[stable(feature = "ord_max_min", since = "1.21.0")]
827 fn min(self, other: Self) -> Self
830 Self: ~const Destruct,
832 // HACK(fee1-dead): go back to using `self.min_by(other, Ord::cmp)`
833 // when trait methods are allowed to be used when a const closure is
835 match self.cmp(&other) {
836 Ordering::Less | Ordering::Equal => self,
837 Ordering::Greater => other,
841 /// Restrict a value to a certain interval.
843 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
844 /// less than `min`. Otherwise this returns `self`.
848 /// Panics if `min > max`.
853 /// assert!((-3).clamp(-2, 1) == -2);
854 /// assert!(0.clamp(-2, 1) == 0);
855 /// assert!(2.clamp(-2, 1) == 1);
858 #[stable(feature = "clamp", since = "1.50.0")]
859 fn clamp(self, min: Self, max: Self) -> Self
862 Self: ~const Destruct,
863 Self: ~const PartialOrd,
868 } else if self > max {
876 /// Derive macro generating an impl of the trait `Ord`.
877 #[rustc_builtin_macro]
878 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
879 #[allow_internal_unstable(core_intrinsics)]
880 pub macro Ord($item:item) {
881 /* compiler built-in */
884 #[stable(feature = "rust1", since = "1.0.0")]
885 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
886 impl const Ord for Ordering {
888 fn cmp(&self, other: &Ordering) -> Ordering {
889 (*self as i32).cmp(&(*other as i32))
893 #[stable(feature = "rust1", since = "1.0.0")]
894 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
895 impl const PartialOrd for Ordering {
897 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
898 (*self as i32).partial_cmp(&(*other as i32))
902 /// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
904 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
905 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
907 /// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
908 /// The following conditions must hold:
910 /// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
911 /// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
912 /// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
913 /// 4. `a <= b` if and only if `a < b || a == b`
914 /// 5. `a >= b` if and only if `a > b || a == b`
915 /// 6. `a != b` if and only if `!(a == b)`.
917 /// Conditions 2–5 above are ensured by the default implementation.
918 /// Condition 6 is already ensured by [`PartialEq`].
920 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
921 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
922 /// easy to accidentally make them disagree by deriving some of the traits and manually
923 /// implementing others.
925 /// The comparison must satisfy, for all `a`, `b` and `c`:
927 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
928 /// - duality: `a < b` if and only if `b > a`.
930 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
931 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
936 /// The following corollaries follow from the above requirements:
938 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
939 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
940 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
944 /// This trait can be used with `#[derive]`.
946 /// When `derive`d on structs, it will produce a
947 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
948 /// based on the top-to-bottom declaration order of the struct's members.
950 /// When `derive`d on enums, variants are ordered by their discriminants.
951 /// By default, the discriminant is smallest for variants at the top, and
952 /// largest for variants at the bottom. Here's an example:
955 /// #[derive(PartialEq, PartialOrd)]
961 /// assert!(E::Top < E::Bottom);
964 /// However, manually setting the discriminants can override this default
968 /// #[derive(PartialEq, PartialOrd)]
974 /// assert!(E::Bottom < E::Top);
977 /// ## How can I implement `PartialOrd`?
979 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
980 /// generated from default implementations.
982 /// However it remains possible to implement the others separately for types which do not have a
983 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
984 /// false` (cf. IEEE 754-2008 section 5.11).
986 /// `PartialOrd` requires your type to be [`PartialEq`].
988 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
991 /// use std::cmp::Ordering;
1000 /// impl PartialOrd for Person {
1001 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1002 /// Some(self.cmp(other))
1006 /// impl Ord for Person {
1007 /// fn cmp(&self, other: &Self) -> Ordering {
1008 /// self.height.cmp(&other.height)
1012 /// impl PartialEq for Person {
1013 /// fn eq(&self, other: &Self) -> bool {
1014 /// self.height == other.height
1019 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
1020 /// is an example of `Person` types who have a floating-point `height` field that
1021 /// is the only field to be used for sorting:
1024 /// use std::cmp::Ordering;
1032 /// impl PartialOrd for Person {
1033 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1034 /// self.height.partial_cmp(&other.height)
1038 /// impl PartialEq for Person {
1039 /// fn eq(&self, other: &Self) -> bool {
1040 /// self.height == other.height
1051 /// assert_eq!(x < y, true);
1052 /// assert_eq!(x.lt(&y), true);
1055 /// [`partial_cmp`]: PartialOrd::partial_cmp
1056 /// [`cmp`]: Ord::cmp
1057 #[lang = "partial_ord"]
1058 #[stable(feature = "rust1", since = "1.0.0")]
1061 #[doc(alias = "<=")]
1062 #[doc(alias = ">=")]
1065 rustc_on_unimplemented(
1066 message = "can't compare `{Self}` with `{Rhs}`",
1067 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1072 rustc_on_unimplemented(
1073 message = "can't compare `{Self}` with `{Rhs}`",
1074 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1079 #[rustc_diagnostic_item = "PartialOrd"]
1080 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
1081 /// This method returns an ordering between `self` and `other` values if one exists.
1086 /// use std::cmp::Ordering;
1088 /// let result = 1.0.partial_cmp(&2.0);
1089 /// assert_eq!(result, Some(Ordering::Less));
1091 /// let result = 1.0.partial_cmp(&1.0);
1092 /// assert_eq!(result, Some(Ordering::Equal));
1094 /// let result = 2.0.partial_cmp(&1.0);
1095 /// assert_eq!(result, Some(Ordering::Greater));
1098 /// When comparison is impossible:
1101 /// let result = f64::NAN.partial_cmp(&1.0);
1102 /// assert_eq!(result, None);
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1108 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1113 /// let result = 1.0 < 2.0;
1114 /// assert_eq!(result, true);
1116 /// let result = 2.0 < 1.0;
1117 /// assert_eq!(result, false);
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 fn lt(&self, other: &Rhs) -> bool {
1123 matches!(self.partial_cmp(other), Some(Less))
1126 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1132 /// let result = 1.0 <= 2.0;
1133 /// assert_eq!(result, true);
1135 /// let result = 2.0 <= 2.0;
1136 /// assert_eq!(result, true);
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 fn le(&self, other: &Rhs) -> bool {
1142 // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`.
1143 // FIXME: The root cause was fixed upstream in LLVM with:
1144 // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775
1145 // Revert this workaround once support for LLVM 12 gets dropped.
1146 !matches!(self.partial_cmp(other), None | Some(Greater))
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 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1234 match compare(&v1, &v2) {
1235 Ordering::Less | Ordering::Equal => v1,
1236 Ordering::Greater => v2,
1240 /// Returns the element that gives the minimum value from the specified function.
1242 /// Returns the first argument if the comparison determines them to be equal.
1249 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1250 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1254 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1255 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1256 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1259 /// Compares and returns the maximum of two values.
1261 /// Returns the second argument if the comparison determines them to be equal.
1263 /// Internally uses an alias to [`Ord::max`].
1270 /// assert_eq!(2, cmp::max(1, 2));
1271 /// assert_eq!(2, cmp::max(2, 2));
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1277 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1278 pub const fn max<T: ~const Ord + ~const Destruct>(v1: T, v2: T) -> T {
1282 /// Returns the maximum of two values with respect to the specified comparison function.
1284 /// Returns the second argument if the comparison determines them to be equal.
1291 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1292 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1296 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1297 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1298 match compare(&v1, &v2) {
1299 Ordering::Less | Ordering::Equal => v2,
1300 Ordering::Greater => v1,
1304 /// Returns the element that gives the maximum value from the specified function.
1306 /// Returns the second argument if the comparison determines them to be equal.
1313 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1314 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1318 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1319 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1320 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1323 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1325 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1326 use crate::hint::unreachable_unchecked;
1328 macro_rules! partial_eq_impl {
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1332 impl const PartialEq for $t {
1334 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1336 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1343 impl const PartialEq for () {
1345 fn eq(&self, _other: &()) -> bool {
1349 fn ne(&self, _other: &()) -> bool {
1355 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1358 macro_rules! eq_impl {
1360 #[stable(feature = "rust1", since = "1.0.0")]
1365 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1367 macro_rules! partial_ord_impl {
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1371 impl const PartialOrd for $t {
1373 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1374 match (*self <= *other, *self >= *other) {
1375 (false, false) => None,
1376 (false, true) => Some(Greater),
1377 (true, false) => Some(Less),
1378 (true, true) => Some(Equal),
1382 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1384 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1386 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1388 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1395 impl const PartialOrd for () {
1397 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1404 impl const PartialOrd for bool {
1406 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1407 Some(self.cmp(other))
1411 partial_ord_impl! { f32 f64 }
1413 macro_rules! ord_impl {
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1417 impl const PartialOrd for $t {
1419 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1420 Some(self.cmp(other))
1423 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1425 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1427 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1429 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1434 impl const Ord for $t {
1436 fn cmp(&self, other: &$t) -> Ordering {
1437 // The order here is important to generate more optimal assembly.
1438 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1439 if *self < *other { Less }
1440 else if *self == *other { Equal }
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1449 impl const Ord for () {
1451 fn cmp(&self, _other: &()) -> Ordering {
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1458 impl const Ord for bool {
1460 fn cmp(&self, other: &bool) -> Ordering {
1461 // Casting to i8's and converting the difference to an Ordering generates
1462 // more optimal assembly.
1463 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1464 match (*self as i8) - (*other as i8) {
1468 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1469 _ => unsafe { unreachable_unchecked() },
1474 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1476 #[unstable(feature = "never_type", issue = "35121")]
1477 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1478 impl const PartialEq for ! {
1479 fn eq(&self, _: &!) -> bool {
1484 #[unstable(feature = "never_type", issue = "35121")]
1487 #[unstable(feature = "never_type", issue = "35121")]
1488 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1489 impl const PartialOrd for ! {
1490 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1495 #[unstable(feature = "never_type", issue = "35121")]
1496 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1497 impl const Ord for ! {
1498 fn cmp(&self, _: &!) -> Ordering {
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1507 impl<A: ?Sized, B: ?Sized> const PartialEq<&B> for &A
1509 A: ~const PartialEq<B>,
1512 fn eq(&self, other: &&B) -> bool {
1513 PartialEq::eq(*self, *other)
1516 fn ne(&self, other: &&B) -> bool {
1517 PartialEq::ne(*self, *other)
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1526 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1527 PartialOrd::partial_cmp(*self, *other)
1530 fn lt(&self, other: &&B) -> bool {
1531 PartialOrd::lt(*self, *other)
1534 fn le(&self, other: &&B) -> bool {
1535 PartialOrd::le(*self, *other)
1538 fn gt(&self, other: &&B) -> bool {
1539 PartialOrd::gt(*self, *other)
1542 fn ge(&self, other: &&B) -> bool {
1543 PartialOrd::ge(*self, *other)
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 impl<A: ?Sized> Ord for &A
1552 fn cmp(&self, other: &Self) -> Ordering {
1553 Ord::cmp(*self, *other)
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 impl<A: ?Sized> Eq for &A where A: Eq {}
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1567 fn eq(&self, other: &&mut B) -> bool {
1568 PartialEq::eq(*self, *other)
1571 fn ne(&self, other: &&mut B) -> bool {
1572 PartialEq::ne(*self, *other)
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1581 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1582 PartialOrd::partial_cmp(*self, *other)
1585 fn lt(&self, other: &&mut B) -> bool {
1586 PartialOrd::lt(*self, *other)
1589 fn le(&self, other: &&mut B) -> bool {
1590 PartialOrd::le(*self, *other)
1593 fn gt(&self, other: &&mut B) -> bool {
1594 PartialOrd::gt(*self, *other)
1597 fn ge(&self, other: &&mut B) -> bool {
1598 PartialOrd::ge(*self, *other)
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 impl<A: ?Sized> Ord for &mut A
1607 fn cmp(&self, other: &Self) -> Ordering {
1608 Ord::cmp(*self, *other)
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1620 fn eq(&self, other: &&mut B) -> bool {
1621 PartialEq::eq(*self, *other)
1624 fn ne(&self, other: &&mut B) -> bool {
1625 PartialEq::ne(*self, *other)
1629 #[stable(feature = "rust1", since = "1.0.0")]
1630 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1635 fn eq(&self, other: &&B) -> bool {
1636 PartialEq::eq(*self, *other)
1639 fn ne(&self, other: &&B) -> bool {
1640 PartialEq::ne(*self, *other)