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 self::Ordering::*;
30 /// Trait for equality comparisons.
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`].
38 /// Formally speaking, when `Rhs == Self`, this trait corresponds to a [partial equivalence
39 /// relation](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
41 /// Implementations must ensure that `eq` and `ne` are consistent with each other:
43 /// - `a != b` if and only if `!(a == b)`.
45 /// The default implementation of `ne` provides this consistency and is almost
46 /// always sufficient. It should not be overridden without very good reason.
48 /// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
49 /// be consistent with `PartialEq` (see the documentation of those traits for the exact
50 /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
51 /// manually implementing others.
53 /// The equality relation `==` must satisfy the following conditions
54 /// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
56 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
57 /// implies `b == a`**; and
59 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
60 /// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
62 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
63 /// (transitive) impls are not forced to exist, but these requirements apply
64 /// whenever they do exist.
68 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
69 /// instances are equal if all fields are equal, and not equal if any fields
70 /// are not equal. When `derive`d on enums, two instances are equal if they
71 /// are the same variant and all fields are equal.
73 /// ## How can I implement `PartialEq`?
75 /// An example implementation for a domain in which two books are considered
76 /// the same book if their ISBN matches, even if the formats differ:
87 /// format: BookFormat,
90 /// impl PartialEq for Book {
91 /// fn eq(&self, other: &Self) -> bool {
92 /// self.isbn == other.isbn
96 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
97 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
98 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
100 /// assert!(b1 == b2);
101 /// assert!(b1 != b3);
104 /// ## How can I compare two different types?
106 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
107 /// For example, let's tweak our previous code a bit:
110 /// // The derive implements <BookFormat> == <BookFormat> comparisons
111 /// #[derive(PartialEq)]
112 /// enum BookFormat {
120 /// format: BookFormat,
123 /// // Implement <Book> == <BookFormat> comparisons
124 /// impl PartialEq<BookFormat> for Book {
125 /// fn eq(&self, other: &BookFormat) -> bool {
126 /// self.format == *other
130 /// // Implement <BookFormat> == <Book> comparisons
131 /// impl PartialEq<Book> for BookFormat {
132 /// fn eq(&self, other: &Book) -> bool {
133 /// *self == other.format
137 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
139 /// assert!(b1 == BookFormat::Paperback);
140 /// assert!(BookFormat::Ebook != b1);
143 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
144 /// we allow `BookFormat`s to be compared with `Book`s.
146 /// A comparison like the one above, which ignores some fields of the struct,
147 /// can be dangerous. It can easily lead to an unintended violation of the
148 /// requirements for a partial equivalence relation. For example, if we kept
149 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
150 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
151 /// via the manual implementation from the first example) then the result would
152 /// violate transitivity:
155 /// #[derive(PartialEq)]
156 /// enum BookFormat {
162 /// #[derive(PartialEq)]
165 /// format: BookFormat,
168 /// impl PartialEq<BookFormat> for Book {
169 /// fn eq(&self, other: &BookFormat) -> bool {
170 /// self.format == *other
174 /// impl PartialEq<Book> for BookFormat {
175 /// fn eq(&self, other: &Book) -> bool {
176 /// *self == other.format
181 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
182 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
184 /// assert!(b1 == BookFormat::Paperback);
185 /// assert!(BookFormat::Paperback == b2);
187 /// // The following should hold by transitivity but doesn't.
188 /// assert!(b1 == b2); // <-- PANICS
198 /// assert_eq!(x == y, false);
199 /// assert_eq!(x.eq(&y), false);
202 /// [`eq`]: PartialEq::eq
203 /// [`ne`]: PartialEq::ne
205 #[stable(feature = "rust1", since = "1.0.0")]
208 #[rustc_on_unimplemented(
209 message = "can't compare `{Self}` with `{Rhs}`",
210 label = "no implementation for `{Self} == {Rhs}`",
214 #[rustc_diagnostic_item = "PartialEq"]
215 pub trait PartialEq<Rhs: ?Sized = Self> {
216 /// This method tests for `self` and `other` values to be equal, and is used
219 #[stable(feature = "rust1", since = "1.0.0")]
220 fn eq(&self, other: &Rhs) -> bool;
222 /// This method tests for `!=`. The default implementation is almost always
223 /// sufficient, and should not be overridden without very good reason.
226 #[stable(feature = "rust1", since = "1.0.0")]
227 fn ne(&self, other: &Rhs) -> bool {
232 /// Derive macro generating an impl of the trait `PartialEq`.
233 #[rustc_builtin_macro]
234 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
235 #[allow_internal_unstable(core_intrinsics, structural_match)]
236 pub macro PartialEq($item:item) {
237 /* compiler built-in */
240 /// Trait for equality comparisons which are [equivalence relations](
241 /// https://en.wikipedia.org/wiki/Equivalence_relation).
243 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
244 /// be (for all `a`, `b` and `c`):
246 /// - reflexive: `a == a`;
247 /// - symmetric: `a == b` implies `b == a`; and
248 /// - transitive: `a == b` and `b == c` implies `a == c`.
250 /// This property cannot be checked by the compiler, and therefore `Eq` implies
251 /// [`PartialEq`], and has no extra methods.
255 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
256 /// no extra methods, it is only informing the compiler that this is an
257 /// equivalence relation rather than a partial equivalence relation. Note that
258 /// the `derive` strategy requires all fields are `Eq`, which isn't
261 /// ## How can I implement `Eq`?
263 /// If you cannot use the `derive` strategy, specify that your type implements
264 /// `Eq`, which has no methods:
267 /// enum BookFormat { Paperback, Hardback, Ebook }
270 /// format: BookFormat,
272 /// impl PartialEq for Book {
273 /// fn eq(&self, other: &Self) -> bool {
274 /// self.isbn == other.isbn
277 /// impl Eq for Book {}
281 #[stable(feature = "rust1", since = "1.0.0")]
282 #[rustc_diagnostic_item = "Eq"]
283 pub trait Eq: PartialEq<Self> {
284 // this method is used solely by #[deriving] to assert
285 // that every component of a type implements #[deriving]
286 // itself, the current deriving infrastructure means doing this
287 // assertion without using a method on this trait is nearly
290 // This should never be implemented by hand.
292 #[no_coverage] // rust-lang/rust#84605
294 #[stable(feature = "rust1", since = "1.0.0")]
295 fn assert_receiver_is_total_eq(&self) {}
298 /// Derive macro generating an impl of the trait `Eq`.
299 #[rustc_builtin_macro]
300 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
301 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
302 pub macro Eq($item:item) {
303 /* compiler built-in */
306 // FIXME: this struct is used solely by #[derive] to
307 // assert that every component of a type implements Eq.
309 // This struct should never appear in user code.
311 #[allow(missing_debug_implementations)]
312 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
313 pub struct AssertParamIsEq<T: Eq + ?Sized> {
314 _field: crate::marker::PhantomData<T>,
317 /// An `Ordering` is the result of a comparison between two values.
322 /// use std::cmp::Ordering;
324 /// let result = 1.cmp(&2);
325 /// assert_eq!(Ordering::Less, result);
327 /// let result = 1.cmp(&1);
328 /// assert_eq!(Ordering::Equal, result);
330 /// let result = 2.cmp(&1);
331 /// assert_eq!(Ordering::Greater, result);
333 #[derive(Clone, Copy, Eq, Debug, Hash)]
334 #[derive_const(PartialOrd, Ord, PartialEq)]
335 #[stable(feature = "rust1", since = "1.0.0")]
338 /// An ordering where a compared value is less than another.
339 #[stable(feature = "rust1", since = "1.0.0")]
341 /// An ordering where a compared value is equal to another.
342 #[stable(feature = "rust1", since = "1.0.0")]
344 /// An ordering where a compared value is greater than another.
345 #[stable(feature = "rust1", since = "1.0.0")]
350 /// Returns `true` if the ordering is the `Equal` variant.
355 /// use std::cmp::Ordering;
357 /// assert_eq!(Ordering::Less.is_eq(), false);
358 /// assert_eq!(Ordering::Equal.is_eq(), true);
359 /// assert_eq!(Ordering::Greater.is_eq(), false);
363 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
364 #[stable(feature = "ordering_helpers", since = "1.53.0")]
365 pub const fn is_eq(self) -> bool {
366 matches!(self, Equal)
369 /// Returns `true` if the ordering is not the `Equal` variant.
374 /// use std::cmp::Ordering;
376 /// assert_eq!(Ordering::Less.is_ne(), true);
377 /// assert_eq!(Ordering::Equal.is_ne(), false);
378 /// assert_eq!(Ordering::Greater.is_ne(), true);
382 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
383 #[stable(feature = "ordering_helpers", since = "1.53.0")]
384 pub const fn is_ne(self) -> bool {
385 !matches!(self, Equal)
388 /// Returns `true` if the ordering is the `Less` variant.
393 /// use std::cmp::Ordering;
395 /// assert_eq!(Ordering::Less.is_lt(), true);
396 /// assert_eq!(Ordering::Equal.is_lt(), false);
397 /// assert_eq!(Ordering::Greater.is_lt(), false);
401 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
402 #[stable(feature = "ordering_helpers", since = "1.53.0")]
403 pub const fn is_lt(self) -> bool {
407 /// Returns `true` if the ordering is the `Greater` variant.
412 /// use std::cmp::Ordering;
414 /// assert_eq!(Ordering::Less.is_gt(), false);
415 /// assert_eq!(Ordering::Equal.is_gt(), false);
416 /// assert_eq!(Ordering::Greater.is_gt(), true);
420 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
421 #[stable(feature = "ordering_helpers", since = "1.53.0")]
422 pub const fn is_gt(self) -> bool {
423 matches!(self, Greater)
426 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
431 /// use std::cmp::Ordering;
433 /// assert_eq!(Ordering::Less.is_le(), true);
434 /// assert_eq!(Ordering::Equal.is_le(), true);
435 /// assert_eq!(Ordering::Greater.is_le(), false);
439 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
440 #[stable(feature = "ordering_helpers", since = "1.53.0")]
441 pub const fn is_le(self) -> bool {
442 !matches!(self, Greater)
445 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
450 /// use std::cmp::Ordering;
452 /// assert_eq!(Ordering::Less.is_ge(), false);
453 /// assert_eq!(Ordering::Equal.is_ge(), true);
454 /// assert_eq!(Ordering::Greater.is_ge(), true);
458 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
459 #[stable(feature = "ordering_helpers", since = "1.53.0")]
460 pub const fn is_ge(self) -> bool {
461 !matches!(self, Less)
464 /// Reverses the `Ordering`.
466 /// * `Less` becomes `Greater`.
467 /// * `Greater` becomes `Less`.
468 /// * `Equal` becomes `Equal`.
475 /// use std::cmp::Ordering;
477 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
478 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
479 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
482 /// This method can be used to reverse a comparison:
485 /// let data: &mut [_] = &mut [2, 10, 5, 8];
487 /// // sort the array from largest to smallest.
488 /// data.sort_by(|a, b| a.cmp(b).reverse());
490 /// let b: &mut [_] = &mut [10, 8, 5, 2];
491 /// assert!(data == b);
495 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub const fn reverse(self) -> Ordering {
505 /// Chains two orderings.
507 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
512 /// use std::cmp::Ordering;
514 /// let result = Ordering::Equal.then(Ordering::Less);
515 /// assert_eq!(result, Ordering::Less);
517 /// let result = Ordering::Less.then(Ordering::Equal);
518 /// assert_eq!(result, Ordering::Less);
520 /// let result = Ordering::Less.then(Ordering::Greater);
521 /// assert_eq!(result, Ordering::Less);
523 /// let result = Ordering::Equal.then(Ordering::Equal);
524 /// assert_eq!(result, Ordering::Equal);
526 /// let x: (i64, i64, i64) = (1, 2, 7);
527 /// let y: (i64, i64, i64) = (1, 5, 3);
528 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
530 /// assert_eq!(result, Ordering::Less);
534 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
535 #[stable(feature = "ordering_chaining", since = "1.17.0")]
536 pub const fn then(self, other: Ordering) -> Ordering {
543 /// Chains the ordering with the given function.
545 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
551 /// use std::cmp::Ordering;
553 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
554 /// assert_eq!(result, Ordering::Less);
556 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
557 /// assert_eq!(result, Ordering::Less);
559 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
560 /// assert_eq!(result, Ordering::Less);
562 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
563 /// assert_eq!(result, Ordering::Equal);
565 /// let x: (i64, i64, i64) = (1, 2, 7);
566 /// let y: (i64, i64, i64) = (1, 5, 3);
567 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
569 /// assert_eq!(result, Ordering::Less);
573 #[stable(feature = "ordering_chaining", since = "1.17.0")]
574 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
582 /// A helper struct for reverse ordering.
584 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
585 /// can be used to reverse order a part of a key.
587 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
592 /// use std::cmp::Reverse;
594 /// let mut v = vec![1, 2, 3, 4, 5, 6];
595 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
596 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
598 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
599 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
601 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
603 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
604 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
605 impl<T: ~const PartialOrd> const PartialOrd for Reverse<T> {
607 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
608 other.0.partial_cmp(&self.0)
612 fn lt(&self, other: &Self) -> bool {
616 fn le(&self, other: &Self) -> bool {
620 fn gt(&self, other: &Self) -> bool {
624 fn ge(&self, other: &Self) -> bool {
629 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
630 impl<T: Ord> Ord for Reverse<T> {
632 fn cmp(&self, other: &Reverse<T>) -> Ordering {
637 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
638 impl<T: Clone> Clone for Reverse<T> {
640 fn clone(&self) -> Reverse<T> {
641 Reverse(self.0.clone())
645 fn clone_from(&mut self, other: &Self) {
646 self.0.clone_from(&other.0)
650 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
652 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
653 /// `max`, `min`, and `clamp` are consistent with `cmp`:
655 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
656 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
657 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
658 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
659 /// (ensured by the default implementation).
661 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
662 /// deriving some of the traits and manually implementing others.
666 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
667 /// This means that for all `a`, `b` and `c`:
669 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
670 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
674 /// This trait can be used with `#[derive]`.
676 /// When `derive`d on structs, it will produce a
677 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
678 /// based on the top-to-bottom declaration order of the struct's members.
680 /// When `derive`d on enums, variants are ordered by their discriminants.
681 /// By default, the discriminant is smallest for variants at the top, and
682 /// largest for variants at the bottom. Here's an example:
685 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
691 /// assert!(E::Top < E::Bottom);
694 /// However, manually setting the discriminants can override this default
698 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
704 /// assert!(E::Bottom < E::Top);
707 /// ## Lexicographical comparison
709 /// Lexicographical comparison is an operation with the following properties:
710 /// - Two sequences are compared element by element.
711 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
712 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
713 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
714 /// - An empty sequence is lexicographically less than any non-empty sequence.
715 /// - Two empty sequences are lexicographically equal.
717 /// ## How can I implement `Ord`?
719 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
721 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
722 /// [`cmp`] on your type's fields.
724 /// Here's an example where you want to sort people by height only, disregarding `id`
728 /// use std::cmp::Ordering;
737 /// impl Ord for Person {
738 /// fn cmp(&self, other: &Self) -> Ordering {
739 /// self.height.cmp(&other.height)
743 /// impl PartialOrd for Person {
744 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
745 /// Some(self.cmp(other))
749 /// impl PartialEq for Person {
750 /// fn eq(&self, other: &Self) -> bool {
751 /// self.height == other.height
756 /// [`cmp`]: Ord::cmp
761 #[stable(feature = "rust1", since = "1.0.0")]
762 #[rustc_diagnostic_item = "Ord"]
764 pub trait Ord: Eq + PartialOrd<Self> {
765 /// This method returns an [`Ordering`] between `self` and `other`.
767 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
768 /// `self <operator> other` if true.
773 /// use std::cmp::Ordering;
775 /// assert_eq!(5.cmp(&10), Ordering::Less);
776 /// assert_eq!(10.cmp(&5), Ordering::Greater);
777 /// assert_eq!(5.cmp(&5), Ordering::Equal);
780 #[stable(feature = "rust1", since = "1.0.0")]
781 fn cmp(&self, other: &Self) -> Ordering;
783 /// Compares and returns the maximum of two values.
785 /// Returns the second argument if the comparison determines them to be equal.
790 /// assert_eq!(2, 1.max(2));
791 /// assert_eq!(2, 2.max(2));
793 #[stable(feature = "ord_max_min", since = "1.21.0")]
796 fn max(self, other: Self) -> Self
799 Self: ~const Destruct,
801 max_by(self, other, Ord::cmp)
804 /// Compares and returns the minimum of two values.
806 /// Returns the first argument if the comparison determines them to be equal.
811 /// assert_eq!(1, 1.min(2));
812 /// assert_eq!(2, 2.min(2));
814 #[stable(feature = "ord_max_min", since = "1.21.0")]
817 fn min(self, other: Self) -> Self
820 Self: ~const Destruct,
822 min_by(self, other, Ord::cmp)
825 /// Restrict a value to a certain interval.
827 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
828 /// less than `min`. Otherwise this returns `self`.
832 /// Panics if `min > max`.
837 /// assert!((-3).clamp(-2, 1) == -2);
838 /// assert!(0.clamp(-2, 1) == 0);
839 /// assert!(2.clamp(-2, 1) == 1);
842 #[stable(feature = "clamp", since = "1.50.0")]
843 fn clamp(self, min: Self, max: Self) -> Self
846 Self: ~const Destruct,
847 Self: ~const PartialOrd,
852 } else if self > max {
860 /// Derive macro generating an impl of the trait `Ord`.
861 #[rustc_builtin_macro]
862 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
863 #[allow_internal_unstable(core_intrinsics)]
864 pub macro Ord($item:item) {
865 /* compiler built-in */
868 /// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
870 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
871 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
873 /// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
874 /// The following conditions must hold:
876 /// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
877 /// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
878 /// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
879 /// 4. `a <= b` if and only if `a < b || a == b`
880 /// 5. `a >= b` if and only if `a > b || a == b`
881 /// 6. `a != b` if and only if `!(a == b)`.
883 /// Conditions 2–5 above are ensured by the default implementation.
884 /// Condition 6 is already ensured by [`PartialEq`].
886 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
887 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
888 /// easy to accidentally make them disagree by deriving some of the traits and manually
889 /// implementing others.
891 /// The comparison must satisfy, for all `a`, `b` and `c`:
893 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
894 /// - duality: `a < b` if and only if `b > a`.
896 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
897 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
902 /// The following corollaries follow from the above requirements:
904 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
905 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
906 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
910 /// This trait can be used with `#[derive]`.
912 /// When `derive`d on structs, it will produce a
913 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
914 /// based on the top-to-bottom declaration order of the struct's members.
916 /// When `derive`d on enums, variants are ordered by their discriminants.
917 /// By default, the discriminant is smallest for variants at the top, and
918 /// largest for variants at the bottom. Here's an example:
921 /// #[derive(PartialEq, PartialOrd)]
927 /// assert!(E::Top < E::Bottom);
930 /// However, manually setting the discriminants can override this default
934 /// #[derive(PartialEq, PartialOrd)]
940 /// assert!(E::Bottom < E::Top);
943 /// ## How can I implement `PartialOrd`?
945 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
946 /// generated from default implementations.
948 /// However it remains possible to implement the others separately for types which do not have a
949 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
950 /// false` (cf. IEEE 754-2008 section 5.11).
952 /// `PartialOrd` requires your type to be [`PartialEq`].
954 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
957 /// use std::cmp::Ordering;
966 /// impl PartialOrd for Person {
967 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
968 /// Some(self.cmp(other))
972 /// impl Ord for Person {
973 /// fn cmp(&self, other: &Self) -> Ordering {
974 /// self.height.cmp(&other.height)
978 /// impl PartialEq for Person {
979 /// fn eq(&self, other: &Self) -> bool {
980 /// self.height == other.height
985 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
986 /// is an example of `Person` types who have a floating-point `height` field that
987 /// is the only field to be used for sorting:
990 /// use std::cmp::Ordering;
998 /// impl PartialOrd for Person {
999 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1000 /// self.height.partial_cmp(&other.height)
1004 /// impl PartialEq for Person {
1005 /// fn eq(&self, other: &Self) -> bool {
1006 /// self.height == other.height
1017 /// assert_eq!(x < y, true);
1018 /// assert_eq!(x.lt(&y), true);
1021 /// [`partial_cmp`]: PartialOrd::partial_cmp
1022 /// [`cmp`]: Ord::cmp
1023 #[lang = "partial_ord"]
1024 #[stable(feature = "rust1", since = "1.0.0")]
1027 #[doc(alias = "<=")]
1028 #[doc(alias = ">=")]
1029 #[rustc_on_unimplemented(
1030 message = "can't compare `{Self}` with `{Rhs}`",
1031 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1035 #[rustc_diagnostic_item = "PartialOrd"]
1036 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
1037 /// This method returns an ordering between `self` and `other` values if one exists.
1042 /// use std::cmp::Ordering;
1044 /// let result = 1.0.partial_cmp(&2.0);
1045 /// assert_eq!(result, Some(Ordering::Less));
1047 /// let result = 1.0.partial_cmp(&1.0);
1048 /// assert_eq!(result, Some(Ordering::Equal));
1050 /// let result = 2.0.partial_cmp(&1.0);
1051 /// assert_eq!(result, Some(Ordering::Greater));
1054 /// When comparison is impossible:
1057 /// let result = f64::NAN.partial_cmp(&1.0);
1058 /// assert_eq!(result, None);
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1064 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1069 /// let result = 1.0 < 2.0;
1070 /// assert_eq!(result, true);
1072 /// let result = 2.0 < 1.0;
1073 /// assert_eq!(result, false);
1077 #[stable(feature = "rust1", since = "1.0.0")]
1078 fn lt(&self, other: &Rhs) -> bool {
1079 matches!(self.partial_cmp(other), Some(Less))
1082 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1088 /// let result = 1.0 <= 2.0;
1089 /// assert_eq!(result, true);
1091 /// let result = 2.0 <= 2.0;
1092 /// assert_eq!(result, true);
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 fn le(&self, other: &Rhs) -> bool {
1098 matches!(self.partial_cmp(other), Some(Less | Equal))
1101 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1106 /// let result = 1.0 > 2.0;
1107 /// assert_eq!(result, false);
1109 /// let result = 2.0 > 2.0;
1110 /// assert_eq!(result, false);
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 fn gt(&self, other: &Rhs) -> bool {
1116 matches!(self.partial_cmp(other), Some(Greater))
1119 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1125 /// let result = 2.0 >= 1.0;
1126 /// assert_eq!(result, true);
1128 /// let result = 2.0 >= 2.0;
1129 /// assert_eq!(result, true);
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 fn ge(&self, other: &Rhs) -> bool {
1135 matches!(self.partial_cmp(other), Some(Greater | Equal))
1139 /// Derive macro generating an impl of the trait `PartialOrd`.
1140 #[rustc_builtin_macro]
1141 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1142 #[allow_internal_unstable(core_intrinsics)]
1143 pub macro PartialOrd($item:item) {
1144 /* compiler built-in */
1147 /// Compares and returns the minimum of two values.
1149 /// Returns the first argument if the comparison determines them to be equal.
1151 /// Internally uses an alias to [`Ord::min`].
1158 /// assert_eq!(1, cmp::min(1, 2));
1159 /// assert_eq!(2, cmp::min(2, 2));
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1165 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1166 pub const fn min<T: ~const Ord + ~const Destruct>(v1: T, v2: T) -> T {
1170 /// Returns the minimum of two values with respect to the specified comparison function.
1172 /// Returns the first argument if the comparison determines them to be equal.
1179 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1180 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1184 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1185 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1186 pub const fn min_by<T, F: ~const FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T
1191 match compare(&v1, &v2) {
1192 Ordering::Less | Ordering::Equal => v1,
1193 Ordering::Greater => v2,
1197 /// Returns the element that gives the minimum value from the specified function.
1199 /// Returns the first argument if the comparison determines them to be equal.
1206 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1207 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1211 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1212 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1213 pub const fn min_by_key<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(v1: T, v2: T, mut f: F) -> T
1219 min_by(v1, v2, const |v1, v2| f(v1).cmp(&f(v2)))
1222 /// Compares and returns the maximum of two values.
1224 /// Returns the second argument if the comparison determines them to be equal.
1226 /// Internally uses an alias to [`Ord::max`].
1233 /// assert_eq!(2, cmp::max(1, 2));
1234 /// assert_eq!(2, cmp::max(2, 2));
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1240 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1241 pub const fn max<T: ~const Ord + ~const Destruct>(v1: T, v2: T) -> T {
1245 /// Returns the maximum of two values with respect to the specified comparison function.
1247 /// Returns the second argument if the comparison determines them to be equal.
1254 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1255 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.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 max_by<T, F: ~const FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T
1266 match compare(&v1, &v2) {
1267 Ordering::Less | Ordering::Equal => v2,
1268 Ordering::Greater => v1,
1272 /// Returns the element that gives the maximum value from the specified function.
1274 /// Returns the second argument if the comparison determines them to be equal.
1281 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1282 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1286 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1287 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1288 pub const fn max_by_key<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(v1: T, v2: T, mut f: F) -> T
1294 const fn imp<T, F: ~const FnMut(&T) -> K, K: ~const Ord>(
1304 max_by(v1, v2, ConstFnMutClosure::new(&mut f, imp))
1307 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1309 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1310 use crate::hint::unreachable_unchecked;
1312 macro_rules! partial_eq_impl {
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1316 impl const PartialEq for $t {
1318 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1320 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1327 impl const PartialEq for () {
1329 fn eq(&self, _other: &()) -> bool {
1333 fn ne(&self, _other: &()) -> bool {
1339 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1342 macro_rules! eq_impl {
1344 #[stable(feature = "rust1", since = "1.0.0")]
1349 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1351 macro_rules! partial_ord_impl {
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1355 impl const PartialOrd for $t {
1357 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1358 match (*self <= *other, *self >= *other) {
1359 (false, false) => None,
1360 (false, true) => Some(Greater),
1361 (true, false) => Some(Less),
1362 (true, true) => Some(Equal),
1366 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1368 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1370 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1372 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1379 impl const PartialOrd for () {
1381 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1388 impl const PartialOrd for bool {
1390 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1391 Some(self.cmp(other))
1395 partial_ord_impl! { f32 f64 }
1397 macro_rules! ord_impl {
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1401 impl const PartialOrd for $t {
1403 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1404 Some(self.cmp(other))
1407 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1409 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1411 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1413 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1418 impl const Ord for $t {
1420 fn cmp(&self, other: &$t) -> Ordering {
1421 // The order here is important to generate more optimal assembly.
1422 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1423 if *self < *other { Less }
1424 else if *self == *other { Equal }
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1433 impl const Ord for () {
1435 fn cmp(&self, _other: &()) -> Ordering {
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1442 impl const Ord for bool {
1444 fn cmp(&self, other: &bool) -> Ordering {
1445 // Casting to i8's and converting the difference to an Ordering generates
1446 // more optimal assembly.
1447 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1448 match (*self as i8) - (*other as i8) {
1452 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1453 _ => unsafe { unreachable_unchecked() },
1458 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1460 #[unstable(feature = "never_type", issue = "35121")]
1461 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1462 impl const PartialEq for ! {
1463 fn eq(&self, _: &!) -> bool {
1468 #[unstable(feature = "never_type", issue = "35121")]
1471 #[unstable(feature = "never_type", issue = "35121")]
1472 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1473 impl const PartialOrd for ! {
1474 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1479 #[unstable(feature = "never_type", issue = "35121")]
1480 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1481 impl const Ord for ! {
1482 fn cmp(&self, _: &!) -> Ordering {
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 #[rustc_const_unstable(feature = "const_cmp", issue = "92391")]
1491 impl<A: ?Sized, B: ?Sized> const PartialEq<&B> for &A
1493 A: ~const PartialEq<B>,
1496 fn eq(&self, other: &&B) -> bool {
1497 PartialEq::eq(*self, *other)
1500 fn ne(&self, other: &&B) -> bool {
1501 PartialEq::ne(*self, *other)
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1510 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1511 PartialOrd::partial_cmp(*self, *other)
1514 fn lt(&self, other: &&B) -> bool {
1515 PartialOrd::lt(*self, *other)
1518 fn le(&self, other: &&B) -> bool {
1519 PartialOrd::le(*self, *other)
1522 fn gt(&self, other: &&B) -> bool {
1523 PartialOrd::gt(*self, *other)
1526 fn ge(&self, other: &&B) -> bool {
1527 PartialOrd::ge(*self, *other)
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl<A: ?Sized> Ord for &A
1536 fn cmp(&self, other: &Self) -> Ordering {
1537 Ord::cmp(*self, *other)
1540 #[stable(feature = "rust1", since = "1.0.0")]
1541 impl<A: ?Sized> Eq for &A where A: Eq {}
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1551 fn eq(&self, other: &&mut B) -> bool {
1552 PartialEq::eq(*self, *other)
1555 fn ne(&self, other: &&mut B) -> bool {
1556 PartialEq::ne(*self, *other)
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1565 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1566 PartialOrd::partial_cmp(*self, *other)
1569 fn lt(&self, other: &&mut B) -> bool {
1570 PartialOrd::lt(*self, *other)
1573 fn le(&self, other: &&mut B) -> bool {
1574 PartialOrd::le(*self, *other)
1577 fn gt(&self, other: &&mut B) -> bool {
1578 PartialOrd::gt(*self, *other)
1581 fn ge(&self, other: &&mut B) -> bool {
1582 PartialOrd::ge(*self, *other)
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 impl<A: ?Sized> Ord for &mut A
1591 fn cmp(&self, other: &Self) -> Ordering {
1592 Ord::cmp(*self, *other)
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1604 fn eq(&self, other: &&mut B) -> bool {
1605 PartialEq::eq(*self, *other)
1608 fn ne(&self, other: &&mut B) -> bool {
1609 PartialEq::ne(*self, *other)
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1619 fn eq(&self, other: &&B) -> bool {
1620 PartialEq::eq(*self, *other)
1623 fn ne(&self, other: &&B) -> bool {
1624 PartialEq::ne(*self, *other)