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 which are [partial equivalence
33 /// relations](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
35 /// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
36 /// We use the easier-to-read infix notation in the remainder of this documentation.
38 /// This trait allows for partial equality, for types that do not have a full
39 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
40 /// so floating point types implement `PartialEq` but not [`trait@Eq`].
42 /// Implementations must ensure that `eq` and `ne` are consistent with each other:
44 /// - `a != b` if and only if `!(a == b)`.
46 /// The default implementation of `ne` provides this consistency and is almost
47 /// always sufficient. It should not be overridden without very good reason.
49 /// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
50 /// be consistent with `PartialEq` (see the documentation of those traits for the exact
51 /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
52 /// manually implementing others.
54 /// The equality relation `==` must satisfy the following conditions
55 /// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
57 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
58 /// implies `b == a`**; and
60 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
61 /// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
63 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
64 /// (transitive) impls are not forced to exist, but these requirements apply
65 /// whenever they do exist.
69 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
70 /// instances are equal if all fields are equal, and not equal if any fields
71 /// are not equal. When `derive`d on enums, two instances are equal if they
72 /// are the same variant and all fields are equal.
74 /// ## How can I implement `PartialEq`?
76 /// An example implementation for a domain in which two books are considered
77 /// the same book if their ISBN matches, even if the formats differ:
88 /// format: BookFormat,
91 /// impl PartialEq for Book {
92 /// fn eq(&self, other: &Self) -> bool {
93 /// self.isbn == other.isbn
97 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
98 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
99 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
101 /// assert!(b1 == b2);
102 /// assert!(b1 != b3);
105 /// ## How can I compare two different types?
107 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
108 /// For example, let's tweak our previous code a bit:
111 /// // The derive implements <BookFormat> == <BookFormat> comparisons
112 /// #[derive(PartialEq)]
113 /// enum BookFormat {
121 /// format: BookFormat,
124 /// // Implement <Book> == <BookFormat> comparisons
125 /// impl PartialEq<BookFormat> for Book {
126 /// fn eq(&self, other: &BookFormat) -> bool {
127 /// self.format == *other
131 /// // Implement <BookFormat> == <Book> comparisons
132 /// impl PartialEq<Book> for BookFormat {
133 /// fn eq(&self, other: &Book) -> bool {
134 /// *self == other.format
138 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
140 /// assert!(b1 == BookFormat::Paperback);
141 /// assert!(BookFormat::Ebook != b1);
144 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
145 /// we allow `BookFormat`s to be compared with `Book`s.
147 /// A comparison like the one above, which ignores some fields of the struct,
148 /// can be dangerous. It can easily lead to an unintended violation of the
149 /// requirements for a partial equivalence relation. For example, if we kept
150 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
151 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
152 /// via the manual implementation from the first example) then the result would
153 /// violate transitivity:
156 /// #[derive(PartialEq)]
157 /// enum BookFormat {
163 /// #[derive(PartialEq)]
166 /// format: BookFormat,
169 /// impl PartialEq<BookFormat> for Book {
170 /// fn eq(&self, other: &BookFormat) -> bool {
171 /// self.format == *other
175 /// impl PartialEq<Book> for BookFormat {
176 /// fn eq(&self, other: &Book) -> bool {
177 /// *self == other.format
182 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
183 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
185 /// assert!(b1 == BookFormat::Paperback);
186 /// assert!(BookFormat::Paperback == b2);
188 /// // The following should hold by transitivity but doesn't.
189 /// assert!(b1 == b2); // <-- PANICS
199 /// assert_eq!(x == y, false);
200 /// assert_eq!(x.eq(&y), false);
203 /// [`eq`]: PartialEq::eq
204 /// [`ne`]: PartialEq::ne
206 #[stable(feature = "rust1", since = "1.0.0")]
209 #[rustc_on_unimplemented(
210 message = "can't compare `{Self}` with `{Rhs}`",
211 label = "no implementation for `{Self} == {Rhs}`",
215 #[rustc_diagnostic_item = "PartialEq"]
216 pub trait PartialEq<Rhs: ?Sized = Self> {
217 /// This method tests for `self` and `other` values to be equal, and is used
220 #[stable(feature = "rust1", since = "1.0.0")]
221 fn eq(&self, other: &Rhs) -> bool;
223 /// This method tests for `!=`. The default implementation is almost always
224 /// sufficient, and should not be overridden without very good reason.
227 #[stable(feature = "rust1", since = "1.0.0")]
228 fn ne(&self, other: &Rhs) -> bool {
233 /// Derive macro generating an impl of the trait `PartialEq`.
234 #[rustc_builtin_macro]
235 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
236 #[allow_internal_unstable(core_intrinsics, structural_match)]
237 pub macro PartialEq($item:item) {
238 /* compiler built-in */
241 /// Trait for equality comparisons which are [equivalence relations](
242 /// https://en.wikipedia.org/wiki/Equivalence_relation).
244 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
245 /// be (for all `a`, `b` and `c`):
247 /// - reflexive: `a == a`;
248 /// - symmetric: `a == b` implies `b == a`; and
249 /// - transitive: `a == b` and `b == c` implies `a == c`.
251 /// This property cannot be checked by the compiler, and therefore `Eq` implies
252 /// [`PartialEq`], and has no extra methods.
256 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
257 /// no extra methods, it is only informing the compiler that this is an
258 /// equivalence relation rather than a partial equivalence relation. Note that
259 /// the `derive` strategy requires all fields are `Eq`, which isn't
262 /// ## How can I implement `Eq`?
264 /// If you cannot use the `derive` strategy, specify that your type implements
265 /// `Eq`, which has no methods:
268 /// enum BookFormat { Paperback, Hardback, Ebook }
271 /// format: BookFormat,
273 /// impl PartialEq for Book {
274 /// fn eq(&self, other: &Self) -> bool {
275 /// self.isbn == other.isbn
278 /// impl Eq for Book {}
282 #[stable(feature = "rust1", since = "1.0.0")]
283 #[rustc_diagnostic_item = "Eq"]
284 pub trait Eq: PartialEq<Self> {
285 // this method is used solely by #[deriving] to assert
286 // that every component of a type implements #[deriving]
287 // itself, the current deriving infrastructure means doing this
288 // assertion without using a method on this trait is nearly
291 // This should never be implemented by hand.
293 #[no_coverage] // rust-lang/rust#84605
295 #[stable(feature = "rust1", since = "1.0.0")]
296 fn assert_receiver_is_total_eq(&self) {}
299 /// Derive macro generating an impl of the trait `Eq`.
300 #[rustc_builtin_macro]
301 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
302 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
303 pub macro Eq($item:item) {
304 /* compiler built-in */
307 // FIXME: this struct is used solely by #[derive] to
308 // assert that every component of a type implements Eq.
310 // This struct should never appear in user code.
312 #[allow(missing_debug_implementations)]
313 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
314 pub struct AssertParamIsEq<T: Eq + ?Sized> {
315 _field: crate::marker::PhantomData<T>,
318 /// An `Ordering` is the result of a comparison between two values.
323 /// use std::cmp::Ordering;
325 /// let result = 1.cmp(&2);
326 /// assert_eq!(Ordering::Less, result);
328 /// let result = 1.cmp(&1);
329 /// assert_eq!(Ordering::Equal, result);
331 /// let result = 2.cmp(&1);
332 /// assert_eq!(Ordering::Greater, result);
334 #[derive(Clone, Copy, Eq, Debug, Hash)]
335 #[cfg_attr(not(bootstrap), derive_const(PartialOrd, Ord, PartialEq))]
336 #[stable(feature = "rust1", since = "1.0.0")]
339 /// An ordering where a compared value is less than another.
340 #[stable(feature = "rust1", since = "1.0.0")]
342 /// An ordering where a compared value is equal to another.
343 #[stable(feature = "rust1", since = "1.0.0")]
345 /// An ordering where a compared value is greater than another.
346 #[stable(feature = "rust1", since = "1.0.0")]
351 /// Returns `true` if the ordering is the `Equal` variant.
356 /// use std::cmp::Ordering;
358 /// assert_eq!(Ordering::Less.is_eq(), false);
359 /// assert_eq!(Ordering::Equal.is_eq(), true);
360 /// assert_eq!(Ordering::Greater.is_eq(), false);
364 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
365 #[stable(feature = "ordering_helpers", since = "1.53.0")]
366 pub const fn is_eq(self) -> bool {
367 matches!(self, Equal)
370 /// Returns `true` if the ordering is not the `Equal` variant.
375 /// use std::cmp::Ordering;
377 /// assert_eq!(Ordering::Less.is_ne(), true);
378 /// assert_eq!(Ordering::Equal.is_ne(), false);
379 /// assert_eq!(Ordering::Greater.is_ne(), true);
383 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
384 #[stable(feature = "ordering_helpers", since = "1.53.0")]
385 pub const fn is_ne(self) -> bool {
386 !matches!(self, Equal)
389 /// Returns `true` if the ordering is the `Less` variant.
394 /// use std::cmp::Ordering;
396 /// assert_eq!(Ordering::Less.is_lt(), true);
397 /// assert_eq!(Ordering::Equal.is_lt(), false);
398 /// assert_eq!(Ordering::Greater.is_lt(), false);
402 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
403 #[stable(feature = "ordering_helpers", since = "1.53.0")]
404 pub const fn is_lt(self) -> bool {
408 /// Returns `true` if the ordering is the `Greater` variant.
413 /// use std::cmp::Ordering;
415 /// assert_eq!(Ordering::Less.is_gt(), false);
416 /// assert_eq!(Ordering::Equal.is_gt(), false);
417 /// assert_eq!(Ordering::Greater.is_gt(), true);
421 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
422 #[stable(feature = "ordering_helpers", since = "1.53.0")]
423 pub const fn is_gt(self) -> bool {
424 matches!(self, Greater)
427 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
432 /// use std::cmp::Ordering;
434 /// assert_eq!(Ordering::Less.is_le(), true);
435 /// assert_eq!(Ordering::Equal.is_le(), true);
436 /// assert_eq!(Ordering::Greater.is_le(), false);
440 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
441 #[stable(feature = "ordering_helpers", since = "1.53.0")]
442 pub const fn is_le(self) -> bool {
443 !matches!(self, Greater)
446 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
451 /// use std::cmp::Ordering;
453 /// assert_eq!(Ordering::Less.is_ge(), false);
454 /// assert_eq!(Ordering::Equal.is_ge(), true);
455 /// assert_eq!(Ordering::Greater.is_ge(), true);
459 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
460 #[stable(feature = "ordering_helpers", since = "1.53.0")]
461 pub const fn is_ge(self) -> bool {
462 !matches!(self, Less)
465 /// Reverses the `Ordering`.
467 /// * `Less` becomes `Greater`.
468 /// * `Greater` becomes `Less`.
469 /// * `Equal` becomes `Equal`.
476 /// use std::cmp::Ordering;
478 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
479 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
480 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
483 /// This method can be used to reverse a comparison:
486 /// let data: &mut [_] = &mut [2, 10, 5, 8];
488 /// // sort the array from largest to smallest.
489 /// data.sort_by(|a, b| a.cmp(b).reverse());
491 /// let b: &mut [_] = &mut [10, 8, 5, 2];
492 /// assert!(data == b);
496 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub const fn reverse(self) -> Ordering {
506 /// Chains two orderings.
508 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
513 /// use std::cmp::Ordering;
515 /// let result = Ordering::Equal.then(Ordering::Less);
516 /// assert_eq!(result, Ordering::Less);
518 /// let result = Ordering::Less.then(Ordering::Equal);
519 /// assert_eq!(result, Ordering::Less);
521 /// let result = Ordering::Less.then(Ordering::Greater);
522 /// assert_eq!(result, Ordering::Less);
524 /// let result = Ordering::Equal.then(Ordering::Equal);
525 /// assert_eq!(result, Ordering::Equal);
527 /// let x: (i64, i64, i64) = (1, 2, 7);
528 /// let y: (i64, i64, i64) = (1, 5, 3);
529 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
531 /// assert_eq!(result, Ordering::Less);
535 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
536 #[stable(feature = "ordering_chaining", since = "1.17.0")]
537 pub const fn then(self, other: Ordering) -> Ordering {
544 /// Chains the ordering with the given function.
546 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
552 /// use std::cmp::Ordering;
554 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
555 /// assert_eq!(result, Ordering::Less);
557 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
558 /// assert_eq!(result, Ordering::Less);
560 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
561 /// assert_eq!(result, Ordering::Less);
563 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
564 /// assert_eq!(result, Ordering::Equal);
566 /// let x: (i64, i64, i64) = (1, 2, 7);
567 /// let y: (i64, i64, i64) = (1, 5, 3);
568 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
570 /// assert_eq!(result, Ordering::Less);
574 #[stable(feature = "ordering_chaining", since = "1.17.0")]
575 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
583 /// A helper struct for reverse ordering.
585 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
586 /// can be used to reverse order a part of a key.
588 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
593 /// use std::cmp::Reverse;
595 /// let mut v = vec![1, 2, 3, 4, 5, 6];
596 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
597 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
599 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
600 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
602 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
604 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
605 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
606 impl<T: ~const PartialOrd> const PartialOrd for Reverse<T> {
608 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
609 other.0.partial_cmp(&self.0)
613 fn lt(&self, other: &Self) -> bool {
617 fn le(&self, other: &Self) -> bool {
621 fn gt(&self, other: &Self) -> bool {
625 fn ge(&self, other: &Self) -> bool {
630 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
631 impl<T: Ord> Ord for Reverse<T> {
633 fn cmp(&self, other: &Reverse<T>) -> Ordering {
638 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
639 impl<T: Clone> Clone for Reverse<T> {
641 fn clone(&self) -> Reverse<T> {
642 Reverse(self.0.clone())
646 fn clone_from(&mut self, other: &Self) {
647 self.0.clone_from(&other.0)
651 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
653 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
654 /// `max`, `min`, and `clamp` are consistent with `cmp`:
656 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
657 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
658 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
659 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
660 /// (ensured by the default implementation).
662 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
663 /// deriving some of the traits and manually implementing others.
667 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
668 /// This means that for all `a`, `b` and `c`:
670 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
671 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
675 /// This trait can be used with `#[derive]`.
677 /// When `derive`d on structs, it will produce a
678 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
679 /// based on the top-to-bottom declaration order of the struct's members.
681 /// When `derive`d on enums, variants are ordered by their discriminants.
682 /// By default, the discriminant is smallest for variants at the top, and
683 /// largest for variants at the bottom. Here's an example:
686 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
692 /// assert!(E::Top < E::Bottom);
695 /// However, manually setting the discriminants can override this default
699 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
705 /// assert!(E::Bottom < E::Top);
708 /// ## Lexicographical comparison
710 /// Lexicographical comparison is an operation with the following properties:
711 /// - Two sequences are compared element by element.
712 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
713 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
714 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
715 /// - An empty sequence is lexicographically less than any non-empty sequence.
716 /// - Two empty sequences are lexicographically equal.
718 /// ## How can I implement `Ord`?
720 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
722 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
723 /// [`cmp`] on your type's fields.
725 /// Here's an example where you want to sort people by height only, disregarding `id`
729 /// use std::cmp::Ordering;
738 /// impl Ord for Person {
739 /// fn cmp(&self, other: &Self) -> Ordering {
740 /// self.height.cmp(&other.height)
744 /// impl PartialOrd for Person {
745 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
746 /// Some(self.cmp(other))
750 /// impl PartialEq for Person {
751 /// fn eq(&self, other: &Self) -> bool {
752 /// self.height == other.height
757 /// [`cmp`]: Ord::cmp
762 #[stable(feature = "rust1", since = "1.0.0")]
763 #[rustc_diagnostic_item = "Ord"]
765 pub trait Ord: Eq + PartialOrd<Self> {
766 /// This method returns an [`Ordering`] between `self` and `other`.
768 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
769 /// `self <operator> other` if true.
774 /// use std::cmp::Ordering;
776 /// assert_eq!(5.cmp(&10), Ordering::Less);
777 /// assert_eq!(10.cmp(&5), Ordering::Greater);
778 /// assert_eq!(5.cmp(&5), Ordering::Equal);
781 #[stable(feature = "rust1", since = "1.0.0")]
782 fn cmp(&self, other: &Self) -> Ordering;
784 /// Compares and returns the maximum of two values.
786 /// Returns the second argument if the comparison determines them to be equal.
791 /// assert_eq!(2, 1.max(2));
792 /// assert_eq!(2, 2.max(2));
794 #[stable(feature = "ord_max_min", since = "1.21.0")]
797 fn max(self, other: Self) -> Self
800 Self: ~const Destruct,
802 // HACK(fee1-dead): go back to using `self.max_by(other, Ord::cmp)`
803 // when trait methods are allowed to be used when a const closure is
805 match self.cmp(&other) {
806 Ordering::Less | Ordering::Equal => other,
807 Ordering::Greater => self,
811 /// Compares and returns the minimum of two values.
813 /// Returns the first argument if the comparison determines them to be equal.
818 /// assert_eq!(1, 1.min(2));
819 /// assert_eq!(2, 2.min(2));
821 #[stable(feature = "ord_max_min", since = "1.21.0")]
824 fn min(self, other: Self) -> Self
827 Self: ~const Destruct,
829 // HACK(fee1-dead): go back to using `self.min_by(other, Ord::cmp)`
830 // when trait methods are allowed to be used when a const closure is
832 match self.cmp(&other) {
833 Ordering::Less | Ordering::Equal => self,
834 Ordering::Greater => other,
838 /// Restrict a value to a certain interval.
840 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
841 /// less than `min`. Otherwise this returns `self`.
845 /// Panics if `min > max`.
850 /// assert!((-3).clamp(-2, 1) == -2);
851 /// assert!(0.clamp(-2, 1) == 0);
852 /// assert!(2.clamp(-2, 1) == 1);
855 #[stable(feature = "clamp", since = "1.50.0")]
856 fn clamp(self, min: Self, max: Self) -> Self
859 Self: ~const Destruct,
860 Self: ~const PartialOrd,
865 } else if self > max {
873 /// Derive macro generating an impl of the trait `Ord`.
874 #[rustc_builtin_macro]
875 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
876 #[allow_internal_unstable(core_intrinsics)]
877 pub macro Ord($item:item) {
878 /* compiler built-in */
881 #[stable(feature = "rust1", since = "1.0.0")]
883 impl StructuralPartialEq for Ordering {}
885 #[stable(feature = "rust1", since = "1.0.0")]
886 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
888 impl const PartialEq for Ordering {
890 fn eq(&self, other: &Self) -> bool {
891 (*self as i32).eq(&(*other as i32))
895 #[stable(feature = "rust1", since = "1.0.0")]
896 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
898 impl const Ord for Ordering {
900 fn cmp(&self, other: &Ordering) -> Ordering {
901 (*self as i32).cmp(&(*other as i32))
905 #[stable(feature = "rust1", since = "1.0.0")]
906 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
908 impl const PartialOrd for Ordering {
910 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
911 (*self as i32).partial_cmp(&(*other as i32))
915 /// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
917 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
918 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
920 /// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
921 /// The following conditions must hold:
923 /// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
924 /// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
925 /// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
926 /// 4. `a <= b` if and only if `a < b || a == b`
927 /// 5. `a >= b` if and only if `a > b || a == b`
928 /// 6. `a != b` if and only if `!(a == b)`.
930 /// Conditions 2–5 above are ensured by the default implementation.
931 /// Condition 6 is already ensured by [`PartialEq`].
933 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
934 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
935 /// easy to accidentally make them disagree by deriving some of the traits and manually
936 /// implementing others.
938 /// The comparison must satisfy, for all `a`, `b` and `c`:
940 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
941 /// - duality: `a < b` if and only if `b > a`.
943 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
944 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
949 /// The following corollaries follow from the above requirements:
951 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
952 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
953 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
957 /// This trait can be used with `#[derive]`.
959 /// When `derive`d on structs, it will produce a
960 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
961 /// based on the top-to-bottom declaration order of the struct's members.
963 /// When `derive`d on enums, variants are ordered by their discriminants.
964 /// By default, the discriminant is smallest for variants at the top, and
965 /// largest for variants at the bottom. Here's an example:
968 /// #[derive(PartialEq, PartialOrd)]
974 /// assert!(E::Top < E::Bottom);
977 /// However, manually setting the discriminants can override this default
981 /// #[derive(PartialEq, PartialOrd)]
987 /// assert!(E::Bottom < E::Top);
990 /// ## How can I implement `PartialOrd`?
992 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
993 /// generated from default implementations.
995 /// However it remains possible to implement the others separately for types which do not have a
996 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
997 /// false` (cf. IEEE 754-2008 section 5.11).
999 /// `PartialOrd` requires your type to be [`PartialEq`].
1001 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
1004 /// use std::cmp::Ordering;
1013 /// impl PartialOrd for Person {
1014 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1015 /// Some(self.cmp(other))
1019 /// impl Ord for Person {
1020 /// fn cmp(&self, other: &Self) -> Ordering {
1021 /// self.height.cmp(&other.height)
1025 /// impl PartialEq for Person {
1026 /// fn eq(&self, other: &Self) -> bool {
1027 /// self.height == other.height
1032 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
1033 /// is an example of `Person` types who have a floating-point `height` field that
1034 /// is the only field to be used for sorting:
1037 /// use std::cmp::Ordering;
1045 /// impl PartialOrd for Person {
1046 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1047 /// self.height.partial_cmp(&other.height)
1051 /// impl PartialEq for Person {
1052 /// fn eq(&self, other: &Self) -> bool {
1053 /// self.height == other.height
1064 /// assert_eq!(x < y, true);
1065 /// assert_eq!(x.lt(&y), true);
1068 /// [`partial_cmp`]: PartialOrd::partial_cmp
1069 /// [`cmp`]: Ord::cmp
1070 #[lang = "partial_ord"]
1071 #[stable(feature = "rust1", since = "1.0.0")]
1074 #[doc(alias = "<=")]
1075 #[doc(alias = ">=")]
1076 #[rustc_on_unimplemented(
1077 message = "can't compare `{Self}` with `{Rhs}`",
1078 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1082 #[rustc_diagnostic_item = "PartialOrd"]
1083 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
1084 /// This method returns an ordering between `self` and `other` values if one exists.
1089 /// use std::cmp::Ordering;
1091 /// let result = 1.0.partial_cmp(&2.0);
1092 /// assert_eq!(result, Some(Ordering::Less));
1094 /// let result = 1.0.partial_cmp(&1.0);
1095 /// assert_eq!(result, Some(Ordering::Equal));
1097 /// let result = 2.0.partial_cmp(&1.0);
1098 /// assert_eq!(result, Some(Ordering::Greater));
1101 /// When comparison is impossible:
1104 /// let result = f64::NAN.partial_cmp(&1.0);
1105 /// assert_eq!(result, None);
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1111 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1116 /// let result = 1.0 < 2.0;
1117 /// assert_eq!(result, true);
1119 /// let result = 2.0 < 1.0;
1120 /// assert_eq!(result, false);
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 fn lt(&self, other: &Rhs) -> bool {
1126 matches!(self.partial_cmp(other), Some(Less))
1129 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1135 /// let result = 1.0 <= 2.0;
1136 /// assert_eq!(result, true);
1138 /// let result = 2.0 <= 2.0;
1139 /// assert_eq!(result, true);
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 fn le(&self, other: &Rhs) -> bool {
1145 matches!(self.partial_cmp(other), Some(Less | Equal))
1148 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1153 /// let result = 1.0 > 2.0;
1154 /// assert_eq!(result, false);
1156 /// let result = 2.0 > 2.0;
1157 /// assert_eq!(result, false);
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 fn gt(&self, other: &Rhs) -> bool {
1163 matches!(self.partial_cmp(other), Some(Greater))
1166 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1172 /// let result = 2.0 >= 1.0;
1173 /// assert_eq!(result, true);
1175 /// let result = 2.0 >= 2.0;
1176 /// assert_eq!(result, true);
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 fn ge(&self, other: &Rhs) -> bool {
1182 matches!(self.partial_cmp(other), Some(Greater | Equal))
1186 /// Derive macro generating an impl of the trait `PartialOrd`.
1187 #[rustc_builtin_macro]
1188 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1189 #[allow_internal_unstable(core_intrinsics)]
1190 pub macro PartialOrd($item:item) {
1191 /* compiler built-in */
1194 /// Compares and returns the minimum of two values.
1196 /// Returns the first argument if the comparison determines them to be equal.
1198 /// Internally uses an alias to [`Ord::min`].
1205 /// assert_eq!(1, cmp::min(1, 2));
1206 /// assert_eq!(2, cmp::min(2, 2));
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1212 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1213 pub const fn min<T: ~const Ord + ~const Destruct>(v1: T, v2: T) -> T {
1217 /// Returns the minimum of two values with respect to the specified comparison function.
1219 /// Returns the first argument if the comparison determines them to be equal.
1226 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1227 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1231 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1232 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1233 pub const fn min_by<T, F: ~const FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T
1238 match compare(&v1, &v2) {
1239 Ordering::Less | Ordering::Equal => v1,
1240 Ordering::Greater => v2,
1244 /// Returns the element that gives the minimum value from the specified function.
1246 /// Returns the first argument if the comparison determines them to be equal.
1253 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1254 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1258 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1259 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1260 pub const fn min_by_key<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(v1: T, v2: T, mut f: F) -> T
1266 const fn imp<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(
1276 min_by(v1, v2, ConstFnMutClosure::new(&mut f, imp))
1279 /// Compares and returns the maximum of two values.
1281 /// Returns the second argument if the comparison determines them to be equal.
1283 /// Internally uses an alias to [`Ord::max`].
1290 /// assert_eq!(2, cmp::max(1, 2));
1291 /// assert_eq!(2, cmp::max(2, 2));
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1297 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1298 pub const fn max<T: ~const Ord + ~const Destruct>(v1: T, v2: T) -> T {
1302 /// Returns the maximum of two values with respect to the specified comparison function.
1304 /// Returns the second argument if the comparison determines them to be equal.
1311 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1312 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1316 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1317 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1318 pub const fn max_by<T, F: ~const FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T
1323 match compare(&v1, &v2) {
1324 Ordering::Less | Ordering::Equal => v2,
1325 Ordering::Greater => v1,
1329 /// Returns the element that gives the maximum value from the specified function.
1331 /// Returns the second argument if the comparison determines them to be equal.
1338 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1339 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1343 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1344 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1345 pub const fn max_by_key<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(v1: T, v2: T, mut f: F) -> T
1351 const fn imp<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(
1361 max_by(v1, v2, ConstFnMutClosure::new(&mut f, imp))
1364 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1366 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1367 use crate::hint::unreachable_unchecked;
1369 macro_rules! partial_eq_impl {
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1373 impl const PartialEq for $t {
1375 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1377 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1384 impl const PartialEq for () {
1386 fn eq(&self, _other: &()) -> bool {
1390 fn ne(&self, _other: &()) -> bool {
1396 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1399 macro_rules! eq_impl {
1401 #[stable(feature = "rust1", since = "1.0.0")]
1406 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1408 macro_rules! partial_ord_impl {
1410 #[stable(feature = "rust1", since = "1.0.0")]
1411 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1412 impl const PartialOrd for $t {
1414 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1415 match (*self <= *other, *self >= *other) {
1416 (false, false) => None,
1417 (false, true) => Some(Greater),
1418 (true, false) => Some(Less),
1419 (true, true) => Some(Equal),
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) }
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1436 impl const PartialOrd for () {
1438 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1445 impl const PartialOrd for bool {
1447 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1448 Some(self.cmp(other))
1452 partial_ord_impl! { f32 f64 }
1454 macro_rules! ord_impl {
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1458 impl const PartialOrd for $t {
1460 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1461 Some(self.cmp(other))
1464 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1466 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1468 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1470 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1475 impl const Ord for $t {
1477 fn cmp(&self, other: &$t) -> Ordering {
1478 // The order here is important to generate more optimal assembly.
1479 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1480 if *self < *other { Less }
1481 else if *self == *other { Equal }
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1490 impl const Ord for () {
1492 fn cmp(&self, _other: &()) -> Ordering {
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1499 impl const Ord for bool {
1501 fn cmp(&self, other: &bool) -> Ordering {
1502 // Casting to i8's and converting the difference to an Ordering generates
1503 // more optimal assembly.
1504 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1505 match (*self as i8) - (*other as i8) {
1509 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1510 _ => unsafe { unreachable_unchecked() },
1515 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1517 #[unstable(feature = "never_type", issue = "35121")]
1518 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1519 impl const PartialEq for ! {
1520 fn eq(&self, _: &!) -> bool {
1525 #[unstable(feature = "never_type", issue = "35121")]
1528 #[unstable(feature = "never_type", issue = "35121")]
1529 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1530 impl const PartialOrd for ! {
1531 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1536 #[unstable(feature = "never_type", issue = "35121")]
1537 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1538 impl const Ord for ! {
1539 fn cmp(&self, _: &!) -> Ordering {
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1548 impl<A: ?Sized, B: ?Sized> const PartialEq<&B> for &A
1550 A: ~const PartialEq<B>,
1553 fn eq(&self, other: &&B) -> bool {
1554 PartialEq::eq(*self, *other)
1557 fn ne(&self, other: &&B) -> bool {
1558 PartialEq::ne(*self, *other)
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1567 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1568 PartialOrd::partial_cmp(*self, *other)
1571 fn lt(&self, other: &&B) -> bool {
1572 PartialOrd::lt(*self, *other)
1575 fn le(&self, other: &&B) -> bool {
1576 PartialOrd::le(*self, *other)
1579 fn gt(&self, other: &&B) -> bool {
1580 PartialOrd::gt(*self, *other)
1583 fn ge(&self, other: &&B) -> bool {
1584 PartialOrd::ge(*self, *other)
1587 #[stable(feature = "rust1", since = "1.0.0")]
1588 impl<A: ?Sized> Ord for &A
1593 fn cmp(&self, other: &Self) -> Ordering {
1594 Ord::cmp(*self, *other)
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<A: ?Sized> Eq for &A where A: Eq {}
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1608 fn eq(&self, other: &&mut B) -> bool {
1609 PartialEq::eq(*self, *other)
1612 fn ne(&self, other: &&mut B) -> bool {
1613 PartialEq::ne(*self, *other)
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1622 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1623 PartialOrd::partial_cmp(*self, *other)
1626 fn lt(&self, other: &&mut B) -> bool {
1627 PartialOrd::lt(*self, *other)
1630 fn le(&self, other: &&mut B) -> bool {
1631 PartialOrd::le(*self, *other)
1634 fn gt(&self, other: &&mut B) -> bool {
1635 PartialOrd::gt(*self, *other)
1638 fn ge(&self, other: &&mut B) -> bool {
1639 PartialOrd::ge(*self, *other)
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 impl<A: ?Sized> Ord for &mut A
1648 fn cmp(&self, other: &Self) -> Ordering {
1649 Ord::cmp(*self, *other)
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1661 fn eq(&self, other: &&mut B) -> bool {
1662 PartialEq::eq(*self, *other)
1665 fn ne(&self, other: &&mut B) -> bool {
1666 PartialEq::ne(*self, *other)
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1676 fn eq(&self, other: &&B) -> bool {
1677 PartialEq::eq(*self, *other)
1680 fn ne(&self, other: &&B) -> bool {
1681 PartialEq::ne(*self, *other)