1 //! Functionality for ordering and comparison.
3 //! This module contains various tools for ordering and comparing values. In
6 //! * [`Eq`] and [`PartialEq`] are traits that allow you to define total and
7 //! partial equality between values, respectively. Implementing them overloads
8 //! the `==` and `!=` operators.
9 //! * [`Ord`] and [`PartialOrd`] are traits that allow you to define total and
10 //! partial orderings between values, respectively. Implementing them overloads
11 //! the `<`, `<=`, `>`, and `>=` operators.
12 //! * [`Ordering`] is an enum returned by the main functions of [`Ord`] and
13 //! [`PartialOrd`], and describes an ordering.
14 //! * [`Reverse`] is a struct that allows you to easily reverse an ordering.
15 //! * [`max`] and [`min`] are functions that build off of [`Ord`] and allow you
16 //! to find the maximum or minimum of two values.
18 //! For more details, see the respective documentation of each item in the list.
23 #![stable(feature = "rust1", since = "1.0.0")]
25 use self::Ordering::*;
27 /// Trait for equality comparisons which are [partial equivalence
28 /// relations](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
30 /// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
31 /// We use the easier-to-read infix notation in the remainder of this documentation.
33 /// This trait allows for partial equality, for types that do not have a full
34 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
35 /// so floating point types implement `PartialEq` but not [`trait@Eq`].
37 /// Implementations must ensure that `eq` and `ne` are consistent with each other:
39 /// - `a != b` if and only if `!(a == b)`
40 /// (ensured by the default implementation).
42 /// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
43 /// be consistent with `PartialEq` (see the documentation of those traits for the exact
44 /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
45 /// manually implementing others.
47 /// The equality relation `==` must satisfy the following conditions
48 /// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
50 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
51 /// implies `b == a`**; and
53 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
54 /// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
56 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
57 /// (transitive) impls are not forced to exist, but these requirements apply
58 /// whenever they do exist.
62 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
63 /// instances are equal if all fields are equal, and not equal if any fields
64 /// are not equal. When `derive`d on enums, each variant is equal to itself
65 /// and not equal to the other variants.
67 /// ## How can I implement `PartialEq`?
69 /// An example implementation for a domain in which two books are considered
70 /// the same book if their ISBN matches, even if the formats differ:
81 /// format: BookFormat,
84 /// impl PartialEq for Book {
85 /// fn eq(&self, other: &Self) -> bool {
86 /// self.isbn == other.isbn
90 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
91 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
92 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
94 /// assert!(b1 == b2);
95 /// assert!(b1 != b3);
98 /// ## How can I compare two different types?
100 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
101 /// For example, let's tweak our previous code a bit:
104 /// // The derive implements <BookFormat> == <BookFormat> comparisons
105 /// #[derive(PartialEq)]
106 /// enum BookFormat {
114 /// format: BookFormat,
117 /// // Implement <Book> == <BookFormat> comparisons
118 /// impl PartialEq<BookFormat> for Book {
119 /// fn eq(&self, other: &BookFormat) -> bool {
120 /// self.format == *other
124 /// // Implement <BookFormat> == <Book> comparisons
125 /// impl PartialEq<Book> for BookFormat {
126 /// fn eq(&self, other: &Book) -> bool {
127 /// *self == other.format
131 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
133 /// assert!(b1 == BookFormat::Paperback);
134 /// assert!(BookFormat::Ebook != b1);
137 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
138 /// we allow `BookFormat`s to be compared with `Book`s.
140 /// A comparison like the one above, which ignores some fields of the struct,
141 /// can be dangerous. It can easily lead to an unintended violation of the
142 /// requirements for a partial equivalence relation. For example, if we kept
143 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
144 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
145 /// via the manual implementation from the first example) then the result would
146 /// violate transitivity:
149 /// #[derive(PartialEq)]
150 /// enum BookFormat {
156 /// #[derive(PartialEq)]
159 /// format: BookFormat,
162 /// impl PartialEq<BookFormat> for Book {
163 /// fn eq(&self, other: &BookFormat) -> bool {
164 /// self.format == *other
168 /// impl PartialEq<Book> for BookFormat {
169 /// fn eq(&self, other: &Book) -> bool {
170 /// *self == other.format
175 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
176 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
178 /// assert!(b1 == BookFormat::Paperback);
179 /// assert!(BookFormat::Paperback == b2);
181 /// // The following should hold by transitivity but doesn't.
182 /// assert!(b1 == b2); // <-- PANICS
192 /// assert_eq!(x == y, false);
193 /// assert_eq!(x.eq(&y), false);
196 /// [`eq`]: PartialEq::eq
197 /// [`ne`]: PartialEq::ne
199 #[stable(feature = "rust1", since = "1.0.0")]
202 #[rustc_on_unimplemented(
203 message = "can't compare `{Self}` with `{Rhs}`",
204 label = "no implementation for `{Self} == {Rhs}`"
206 #[rustc_diagnostic_item = "PartialEq"]
207 pub trait PartialEq<Rhs: ?Sized = Self> {
208 /// This method tests for `self` and `other` values to be equal, and is used
211 #[stable(feature = "rust1", since = "1.0.0")]
212 fn eq(&self, other: &Rhs) -> bool;
214 /// This method tests for `!=`.
217 #[stable(feature = "rust1", since = "1.0.0")]
218 #[default_method_body_is_const]
219 fn ne(&self, other: &Rhs) -> bool {
224 /// Derive macro generating an impl of the trait `PartialEq`.
225 #[rustc_builtin_macro]
226 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
227 #[allow_internal_unstable(core_intrinsics, structural_match)]
228 pub macro PartialEq($item:item) {
229 /* compiler built-in */
232 /// Trait for equality comparisons which are [equivalence relations](
233 /// https://en.wikipedia.org/wiki/Equivalence_relation).
235 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
236 /// be (for all `a`, `b` and `c`):
238 /// - reflexive: `a == a`;
239 /// - symmetric: `a == b` implies `b == a`; and
240 /// - transitive: `a == b` and `b == c` implies `a == c`.
242 /// This property cannot be checked by the compiler, and therefore `Eq` implies
243 /// [`PartialEq`], and has no extra methods.
247 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
248 /// no extra methods, it is only informing the compiler that this is an
249 /// equivalence relation rather than a partial equivalence relation. Note that
250 /// the `derive` strategy requires all fields are `Eq`, which isn't
253 /// ## How can I implement `Eq`?
255 /// If you cannot use the `derive` strategy, specify that your type implements
256 /// `Eq`, which has no methods:
259 /// enum BookFormat { Paperback, Hardback, Ebook }
262 /// format: BookFormat,
264 /// impl PartialEq for Book {
265 /// fn eq(&self, other: &Self) -> bool {
266 /// self.isbn == other.isbn
269 /// impl Eq for Book {}
273 #[stable(feature = "rust1", since = "1.0.0")]
274 #[rustc_diagnostic_item = "Eq"]
275 pub trait Eq: PartialEq<Self> {
276 // this method is used solely by #[deriving] to assert
277 // that every component of a type implements #[deriving]
278 // itself, the current deriving infrastructure means doing this
279 // assertion without using a method on this trait is nearly
282 // This should never be implemented by hand.
284 #[no_coverage] // rust-lang/rust#84605
286 #[stable(feature = "rust1", since = "1.0.0")]
287 fn assert_receiver_is_total_eq(&self) {}
290 /// Derive macro generating an impl of the trait `Eq`.
291 #[rustc_builtin_macro]
292 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
293 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
294 pub macro Eq($item:item) {
295 /* compiler built-in */
298 // FIXME: this struct is used solely by #[derive] to
299 // assert that every component of a type implements Eq.
301 // This struct should never appear in user code.
303 #[allow(missing_debug_implementations)]
304 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
305 pub struct AssertParamIsEq<T: Eq + ?Sized> {
306 _field: crate::marker::PhantomData<T>,
309 /// An `Ordering` is the result of a comparison between two values.
314 /// use std::cmp::Ordering;
316 /// let result = 1.cmp(&2);
317 /// assert_eq!(Ordering::Less, result);
319 /// let result = 1.cmp(&1);
320 /// assert_eq!(Ordering::Equal, result);
322 /// let result = 2.cmp(&1);
323 /// assert_eq!(Ordering::Greater, result);
325 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
326 #[stable(feature = "rust1", since = "1.0.0")]
329 /// An ordering where a compared value is less than another.
330 #[stable(feature = "rust1", since = "1.0.0")]
332 /// An ordering where a compared value is equal to another.
333 #[stable(feature = "rust1", since = "1.0.0")]
335 /// An ordering where a compared value is greater than another.
336 #[stable(feature = "rust1", since = "1.0.0")]
341 /// Returns `true` if the ordering is the `Equal` variant.
346 /// use std::cmp::Ordering;
348 /// assert_eq!(Ordering::Less.is_eq(), false);
349 /// assert_eq!(Ordering::Equal.is_eq(), true);
350 /// assert_eq!(Ordering::Greater.is_eq(), false);
354 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
355 #[stable(feature = "ordering_helpers", since = "1.53.0")]
356 pub const fn is_eq(self) -> bool {
357 matches!(self, Equal)
360 /// Returns `true` if the ordering is not the `Equal` variant.
365 /// use std::cmp::Ordering;
367 /// assert_eq!(Ordering::Less.is_ne(), true);
368 /// assert_eq!(Ordering::Equal.is_ne(), false);
369 /// assert_eq!(Ordering::Greater.is_ne(), true);
373 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
374 #[stable(feature = "ordering_helpers", since = "1.53.0")]
375 pub const fn is_ne(self) -> bool {
376 !matches!(self, Equal)
379 /// Returns `true` if the ordering is the `Less` variant.
384 /// use std::cmp::Ordering;
386 /// assert_eq!(Ordering::Less.is_lt(), true);
387 /// assert_eq!(Ordering::Equal.is_lt(), false);
388 /// assert_eq!(Ordering::Greater.is_lt(), false);
392 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
393 #[stable(feature = "ordering_helpers", since = "1.53.0")]
394 pub const fn is_lt(self) -> bool {
398 /// Returns `true` if the ordering is the `Greater` variant.
403 /// use std::cmp::Ordering;
405 /// assert_eq!(Ordering::Less.is_gt(), false);
406 /// assert_eq!(Ordering::Equal.is_gt(), false);
407 /// assert_eq!(Ordering::Greater.is_gt(), true);
411 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
412 #[stable(feature = "ordering_helpers", since = "1.53.0")]
413 pub const fn is_gt(self) -> bool {
414 matches!(self, Greater)
417 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
422 /// use std::cmp::Ordering;
424 /// assert_eq!(Ordering::Less.is_le(), true);
425 /// assert_eq!(Ordering::Equal.is_le(), true);
426 /// assert_eq!(Ordering::Greater.is_le(), false);
430 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
431 #[stable(feature = "ordering_helpers", since = "1.53.0")]
432 pub const fn is_le(self) -> bool {
433 !matches!(self, Greater)
436 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
441 /// use std::cmp::Ordering;
443 /// assert_eq!(Ordering::Less.is_ge(), false);
444 /// assert_eq!(Ordering::Equal.is_ge(), true);
445 /// assert_eq!(Ordering::Greater.is_ge(), true);
449 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
450 #[stable(feature = "ordering_helpers", since = "1.53.0")]
451 pub const fn is_ge(self) -> bool {
452 !matches!(self, Less)
455 /// Reverses the `Ordering`.
457 /// * `Less` becomes `Greater`.
458 /// * `Greater` becomes `Less`.
459 /// * `Equal` becomes `Equal`.
466 /// use std::cmp::Ordering;
468 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
469 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
470 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
473 /// This method can be used to reverse a comparison:
476 /// let data: &mut [_] = &mut [2, 10, 5, 8];
478 /// // sort the array from largest to smallest.
479 /// data.sort_by(|a, b| a.cmp(b).reverse());
481 /// let b: &mut [_] = &mut [10, 8, 5, 2];
482 /// assert!(data == b);
486 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
487 #[stable(feature = "rust1", since = "1.0.0")]
488 pub const fn reverse(self) -> Ordering {
496 /// Chains two orderings.
498 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
503 /// use std::cmp::Ordering;
505 /// let result = Ordering::Equal.then(Ordering::Less);
506 /// assert_eq!(result, Ordering::Less);
508 /// let result = Ordering::Less.then(Ordering::Equal);
509 /// assert_eq!(result, Ordering::Less);
511 /// let result = Ordering::Less.then(Ordering::Greater);
512 /// assert_eq!(result, Ordering::Less);
514 /// let result = Ordering::Equal.then(Ordering::Equal);
515 /// assert_eq!(result, Ordering::Equal);
517 /// let x: (i64, i64, i64) = (1, 2, 7);
518 /// let y: (i64, i64, i64) = (1, 5, 3);
519 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
521 /// assert_eq!(result, Ordering::Less);
525 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
526 #[stable(feature = "ordering_chaining", since = "1.17.0")]
527 pub const fn then(self, other: Ordering) -> Ordering {
534 /// Chains the ordering with the given function.
536 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
542 /// use std::cmp::Ordering;
544 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
545 /// assert_eq!(result, Ordering::Less);
547 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
548 /// assert_eq!(result, Ordering::Less);
550 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
551 /// assert_eq!(result, Ordering::Less);
553 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
554 /// assert_eq!(result, Ordering::Equal);
556 /// let x: (i64, i64, i64) = (1, 2, 7);
557 /// let y: (i64, i64, i64) = (1, 5, 3);
558 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
560 /// assert_eq!(result, Ordering::Less);
564 #[stable(feature = "ordering_chaining", since = "1.17.0")]
565 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
573 /// A helper struct for reverse ordering.
575 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
576 /// can be used to reverse order a part of a key.
578 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
583 /// use std::cmp::Reverse;
585 /// let mut v = vec![1, 2, 3, 4, 5, 6];
586 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
587 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
589 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
590 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
592 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
594 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
595 impl<T: PartialOrd> PartialOrd for Reverse<T> {
597 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
598 other.0.partial_cmp(&self.0)
602 fn lt(&self, other: &Self) -> bool {
606 fn le(&self, other: &Self) -> bool {
610 fn gt(&self, other: &Self) -> bool {
614 fn ge(&self, other: &Self) -> bool {
619 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
620 impl<T: Ord> Ord for Reverse<T> {
622 fn cmp(&self, other: &Reverse<T>) -> Ordering {
627 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
628 impl<T: Clone> Clone for Reverse<T> {
630 fn clone(&self) -> Reverse<T> {
631 Reverse(self.0.clone())
635 fn clone_from(&mut self, other: &Self) {
636 self.0.clone_from(&other.0)
640 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
642 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
643 /// `max`, `min`, and `clamp` are consistent with `cmp`:
645 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
646 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
647 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
648 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
649 /// (ensured by the default implementation).
651 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
652 /// deriving some of the traits and manually implementing others.
656 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
657 /// This means that for all `a`, `b` and `c`:
659 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
660 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
664 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
665 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the top-to-bottom declaration order of the struct's members.
666 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
667 /// This means variants at the top are less than variants at the bottom.
668 /// Here's an example:
671 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
677 /// assert!(Size::Small < Size::Large);
680 /// ## Lexicographical comparison
682 /// Lexicographical comparison is an operation with the following properties:
683 /// - Two sequences are compared element by element.
684 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
685 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
686 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
687 /// - An empty sequence is lexicographically less than any non-empty sequence.
688 /// - Two empty sequences are lexicographically equal.
690 /// ## How can I implement `Ord`?
692 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
694 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
695 /// [`cmp`] on your type's fields.
697 /// Here's an example where you want to sort people by height only, disregarding `id`
701 /// use std::cmp::Ordering;
710 /// impl Ord for Person {
711 /// fn cmp(&self, other: &Self) -> Ordering {
712 /// self.height.cmp(&other.height)
716 /// impl PartialOrd for Person {
717 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
718 /// Some(self.cmp(other))
722 /// impl PartialEq for Person {
723 /// fn eq(&self, other: &Self) -> bool {
724 /// self.height == other.height
729 /// [`cmp`]: Ord::cmp
734 #[stable(feature = "rust1", since = "1.0.0")]
735 #[rustc_diagnostic_item = "Ord"]
736 pub trait Ord: Eq + PartialOrd<Self> {
737 /// This method returns an [`Ordering`] between `self` and `other`.
739 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
740 /// `self <operator> other` if true.
745 /// use std::cmp::Ordering;
747 /// assert_eq!(5.cmp(&10), Ordering::Less);
748 /// assert_eq!(10.cmp(&5), Ordering::Greater);
749 /// assert_eq!(5.cmp(&5), Ordering::Equal);
752 #[stable(feature = "rust1", since = "1.0.0")]
753 fn cmp(&self, other: &Self) -> Ordering;
755 /// Compares and returns the maximum of two values.
757 /// Returns the second argument if the comparison determines them to be equal.
762 /// assert_eq!(2, 1.max(2));
763 /// assert_eq!(2, 2.max(2));
765 #[stable(feature = "ord_max_min", since = "1.21.0")]
768 fn max(self, other: Self) -> Self
772 max_by(self, other, Ord::cmp)
775 /// Compares and returns the minimum of two values.
777 /// Returns the first argument if the comparison determines them to be equal.
782 /// assert_eq!(1, 1.min(2));
783 /// assert_eq!(2, 2.min(2));
785 #[stable(feature = "ord_max_min", since = "1.21.0")]
788 fn min(self, other: Self) -> Self
792 min_by(self, other, Ord::cmp)
795 /// Restrict a value to a certain interval.
797 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
798 /// less than `min`. Otherwise this returns `self`.
802 /// Panics if `min > max`.
807 /// assert!((-3).clamp(-2, 1) == -2);
808 /// assert!(0.clamp(-2, 1) == 0);
809 /// assert!(2.clamp(-2, 1) == 1);
812 #[stable(feature = "clamp", since = "1.50.0")]
813 fn clamp(self, min: Self, max: Self) -> Self
820 } else if self > max {
828 /// Derive macro generating an impl of the trait `Ord`.
829 #[rustc_builtin_macro]
830 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
831 #[allow_internal_unstable(core_intrinsics)]
832 pub macro Ord($item:item) {
833 /* compiler built-in */
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl Eq for Ordering {}
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl Ord for Ordering {
842 fn cmp(&self, other: &Ordering) -> Ordering {
843 (*self as i32).cmp(&(*other as i32))
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl PartialOrd for Ordering {
850 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
851 (*self as i32).partial_cmp(&(*other as i32))
855 /// Trait for values that can be compared for a sort-order.
857 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
858 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
860 /// The methods of this trait must be consistent with each other and with those of `PartialEq` in
861 /// the following sense:
863 /// - `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
864 /// - `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
865 /// (ensured by the default implementation).
866 /// - `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
867 /// (ensured by the default implementation).
868 /// - `a <= b` if and only if `a < b || a == b`
869 /// (ensured by the default implementation).
870 /// - `a >= b` if and only if `a > b || a == b`
871 /// (ensured by the default implementation).
872 /// - `a != b` if and only if `!(a == b)` (already part of `PartialEq`).
874 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
875 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
876 /// easy to accidentally make them disagree by deriving some of the traits and manually
877 /// implementing others.
879 /// The comparison must satisfy, for all `a`, `b` and `c`:
881 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
882 /// - duality: `a < b` if and only if `b > a`.
884 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
885 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
890 /// The following corollaries follow from the above requirements:
892 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
893 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
894 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
898 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
899 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
900 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
901 /// This means variants at the top are less than variants at the bottom.
902 /// Here's an example:
905 /// #[derive(PartialEq, PartialOrd)]
911 /// assert!(Size::Small < Size::Large);
914 /// ## How can I implement `PartialOrd`?
916 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
917 /// generated from default implementations.
919 /// However it remains possible to implement the others separately for types which do not have a
920 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
921 /// false` (cf. IEEE 754-2008 section 5.11).
923 /// `PartialOrd` requires your type to be [`PartialEq`].
925 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
928 /// use std::cmp::Ordering;
937 /// impl PartialOrd for Person {
938 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
939 /// Some(self.cmp(other))
943 /// impl Ord for Person {
944 /// fn cmp(&self, other: &Self) -> Ordering {
945 /// self.height.cmp(&other.height)
949 /// impl PartialEq for Person {
950 /// fn eq(&self, other: &Self) -> bool {
951 /// self.height == other.height
956 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
957 /// is an example of `Person` types who have a floating-point `height` field that
958 /// is the only field to be used for sorting:
961 /// use std::cmp::Ordering;
969 /// impl PartialOrd for Person {
970 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
971 /// self.height.partial_cmp(&other.height)
975 /// impl PartialEq for Person {
976 /// fn eq(&self, other: &Self) -> bool {
977 /// self.height == other.height
988 /// assert_eq!(x < y, true);
989 /// assert_eq!(x.lt(&y), true);
992 /// [`partial_cmp`]: PartialOrd::partial_cmp
993 /// [`cmp`]: Ord::cmp
994 #[lang = "partial_ord"]
995 #[stable(feature = "rust1", since = "1.0.0")]
1000 #[rustc_on_unimplemented(
1001 message = "can't compare `{Self}` with `{Rhs}`",
1002 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
1004 #[rustc_diagnostic_item = "PartialOrd"]
1005 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
1006 /// This method returns an ordering between `self` and `other` values if one exists.
1011 /// use std::cmp::Ordering;
1013 /// let result = 1.0.partial_cmp(&2.0);
1014 /// assert_eq!(result, Some(Ordering::Less));
1016 /// let result = 1.0.partial_cmp(&1.0);
1017 /// assert_eq!(result, Some(Ordering::Equal));
1019 /// let result = 2.0.partial_cmp(&1.0);
1020 /// assert_eq!(result, Some(Ordering::Greater));
1023 /// When comparison is impossible:
1026 /// let result = f64::NAN.partial_cmp(&1.0);
1027 /// assert_eq!(result, None);
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1033 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1038 /// let result = 1.0 < 2.0;
1039 /// assert_eq!(result, true);
1041 /// let result = 2.0 < 1.0;
1042 /// assert_eq!(result, false);
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 #[default_method_body_is_const]
1048 fn lt(&self, other: &Rhs) -> bool {
1049 matches!(self.partial_cmp(other), Some(Less))
1052 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1058 /// let result = 1.0 <= 2.0;
1059 /// assert_eq!(result, true);
1061 /// let result = 2.0 <= 2.0;
1062 /// assert_eq!(result, true);
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 #[default_method_body_is_const]
1068 fn le(&self, other: &Rhs) -> bool {
1069 // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`.
1070 // FIXME: The root cause was fixed upstream in LLVM with:
1071 // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775
1072 // Revert this workaround once support for LLVM 12 gets dropped.
1073 !matches!(self.partial_cmp(other), None | Some(Greater))
1076 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1081 /// let result = 1.0 > 2.0;
1082 /// assert_eq!(result, false);
1084 /// let result = 2.0 > 2.0;
1085 /// assert_eq!(result, false);
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 #[default_method_body_is_const]
1091 fn gt(&self, other: &Rhs) -> bool {
1092 matches!(self.partial_cmp(other), Some(Greater))
1095 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1101 /// let result = 2.0 >= 1.0;
1102 /// assert_eq!(result, true);
1104 /// let result = 2.0 >= 2.0;
1105 /// assert_eq!(result, true);
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 #[default_method_body_is_const]
1111 fn ge(&self, other: &Rhs) -> bool {
1112 matches!(self.partial_cmp(other), Some(Greater | Equal))
1116 /// Derive macro generating an impl of the trait `PartialOrd`.
1117 #[rustc_builtin_macro]
1118 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1119 #[allow_internal_unstable(core_intrinsics)]
1120 pub macro PartialOrd($item:item) {
1121 /* compiler built-in */
1124 /// Compares and returns the minimum of two values.
1126 /// Returns the first argument if the comparison determines them to be equal.
1128 /// Internally uses an alias to [`Ord::min`].
1135 /// assert_eq!(1, cmp::min(1, 2));
1136 /// assert_eq!(2, cmp::min(2, 2));
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1142 pub fn min<T: Ord>(v1: T, v2: T) -> T {
1146 /// Returns the minimum of two values with respect to the specified comparison function.
1148 /// Returns the first argument if the comparison determines them to be equal.
1155 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1156 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1160 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1161 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1162 match compare(&v1, &v2) {
1163 Ordering::Less | Ordering::Equal => v1,
1164 Ordering::Greater => v2,
1168 /// Returns the element that gives the minimum value from the specified function.
1170 /// Returns the first argument if the comparison determines them to be equal.
1177 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1178 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1182 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1183 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1184 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1187 /// Compares and returns the maximum of two values.
1189 /// Returns the second argument if the comparison determines them to be equal.
1191 /// Internally uses an alias to [`Ord::max`].
1198 /// assert_eq!(2, cmp::max(1, 2));
1199 /// assert_eq!(2, cmp::max(2, 2));
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1205 pub fn max<T: Ord>(v1: T, v2: T) -> T {
1209 /// Returns the maximum of two values with respect to the specified comparison function.
1211 /// Returns the second argument if the comparison determines them to be equal.
1218 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1219 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1223 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1224 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1225 match compare(&v1, &v2) {
1226 Ordering::Less | Ordering::Equal => v2,
1227 Ordering::Greater => v1,
1231 /// Returns the element that gives the maximum value from the specified function.
1233 /// Returns the second argument if the comparison determines them to be equal.
1240 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1241 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1245 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1246 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1247 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1250 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1252 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1253 use crate::hint::unreachable_unchecked;
1255 macro_rules! partial_eq_impl {
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 impl PartialEq for $t {
1260 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1262 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 impl PartialEq for () {
1270 fn eq(&self, _other: &()) -> bool {
1274 fn ne(&self, _other: &()) -> bool {
1280 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1283 macro_rules! eq_impl {
1285 #[stable(feature = "rust1", since = "1.0.0")]
1290 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1292 macro_rules! partial_ord_impl {
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 impl PartialOrd for $t {
1297 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1298 match (self <= other, self >= other) {
1299 (false, false) => None,
1300 (false, true) => Some(Greater),
1301 (true, false) => Some(Less),
1302 (true, true) => Some(Equal),
1306 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1308 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1310 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1312 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 impl PartialOrd for () {
1320 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl PartialOrd for bool {
1328 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1329 Some(self.cmp(other))
1333 partial_ord_impl! { f32 f64 }
1335 macro_rules! ord_impl {
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 impl PartialOrd for $t {
1340 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1341 Some(self.cmp(other))
1344 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1346 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1348 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1350 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1353 #[stable(feature = "rust1", since = "1.0.0")]
1356 fn cmp(&self, other: &$t) -> Ordering {
1357 // The order here is important to generate more optimal assembly.
1358 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1359 if *self < *other { Less }
1360 else if *self == *other { Equal }
1367 #[stable(feature = "rust1", since = "1.0.0")]
1370 fn cmp(&self, _other: &()) -> Ordering {
1375 #[stable(feature = "rust1", since = "1.0.0")]
1378 fn cmp(&self, other: &bool) -> Ordering {
1379 // Casting to i8's and converting the difference to an Ordering generates
1380 // more optimal assembly.
1381 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1382 match (*self as i8) - (*other as i8) {
1386 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1387 _ => unsafe { unreachable_unchecked() },
1392 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1394 #[unstable(feature = "never_type", issue = "35121")]
1395 impl PartialEq for ! {
1396 fn eq(&self, _: &!) -> bool {
1401 #[unstable(feature = "never_type", issue = "35121")]
1404 #[unstable(feature = "never_type", issue = "35121")]
1405 impl PartialOrd for ! {
1406 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1411 #[unstable(feature = "never_type", issue = "35121")]
1413 fn cmp(&self, _: &!) -> Ordering {
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
1426 fn eq(&self, other: &&B) -> bool {
1427 PartialEq::eq(*self, *other)
1430 fn ne(&self, other: &&B) -> bool {
1431 PartialEq::ne(*self, *other)
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1440 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1441 PartialOrd::partial_cmp(*self, *other)
1444 fn lt(&self, other: &&B) -> bool {
1445 PartialOrd::lt(*self, *other)
1448 fn le(&self, other: &&B) -> bool {
1449 PartialOrd::le(*self, *other)
1452 fn gt(&self, other: &&B) -> bool {
1453 PartialOrd::gt(*self, *other)
1456 fn ge(&self, other: &&B) -> bool {
1457 PartialOrd::ge(*self, *other)
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl<A: ?Sized> Ord for &A
1466 fn cmp(&self, other: &Self) -> Ordering {
1467 Ord::cmp(*self, *other)
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<A: ?Sized> Eq for &A where A: Eq {}
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1481 fn eq(&self, other: &&mut B) -> bool {
1482 PartialEq::eq(*self, *other)
1485 fn ne(&self, other: &&mut B) -> bool {
1486 PartialEq::ne(*self, *other)
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1495 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1496 PartialOrd::partial_cmp(*self, *other)
1499 fn lt(&self, other: &&mut B) -> bool {
1500 PartialOrd::lt(*self, *other)
1503 fn le(&self, other: &&mut B) -> bool {
1504 PartialOrd::le(*self, *other)
1507 fn gt(&self, other: &&mut B) -> bool {
1508 PartialOrd::gt(*self, *other)
1511 fn ge(&self, other: &&mut B) -> bool {
1512 PartialOrd::ge(*self, *other)
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 impl<A: ?Sized> Ord for &mut A
1521 fn cmp(&self, other: &Self) -> Ordering {
1522 Ord::cmp(*self, *other)
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1534 fn eq(&self, other: &&mut B) -> bool {
1535 PartialEq::eq(*self, *other)
1538 fn ne(&self, other: &&mut B) -> bool {
1539 PartialEq::ne(*self, *other)
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1549 fn eq(&self, other: &&B) -> bool {
1550 PartialEq::eq(*self, *other)
1553 fn ne(&self, other: &&B) -> bool {
1554 PartialEq::ne(*self, *other)