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.
20 //! [`Eq`]: trait.Eq.html
21 //! [`PartialEq`]: trait.PartialEq.html
22 //! [`Ord`]: trait.Ord.html
23 //! [`PartialOrd`]: trait.PartialOrd.html
24 //! [`Ordering`]: enum.Ordering.html
25 //! [`Reverse`]: struct.Reverse.html
26 //! [`max`]: fn.max.html
27 //! [`min`]: fn.min.html
29 #![stable(feature = "rust1", since = "1.0.0")]
31 use self::Ordering::*;
33 /// Trait for equality comparisons which are [partial equivalence
34 /// relations](http://en.wikipedia.org/wiki/Partial_equivalence_relation).
36 /// This trait allows for partial equality, for types that do not have a full
37 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
38 /// so floating point types implement `PartialEq` but not `Eq`.
40 /// Formally, the equality must be (for all `a`, `b` and `c`):
42 /// - symmetric: `a == b` implies `b == a`; and
43 /// - transitive: `a == b` and `b == c` implies `a == c`.
45 /// Note that these requirements mean that the trait itself must be implemented
46 /// symmetrically and transitively: if `T: PartialEq<U>` and `U: PartialEq<V>`
47 /// then `U: PartialEq<T>` and `T: PartialEq<V>`.
51 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
52 /// instances are equal if all fields are equal, and not equal if any fields
53 /// are not equal. When `derive`d on enums, each variant is equal to itself
54 /// and not equal to the other variants.
56 /// ## How can I implement `PartialEq`?
58 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined
59 /// in terms of it by default. Any manual implementation of `ne` *must* respect
60 /// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
63 /// Implementations of `PartialEq`, `PartialOrd`, and `Ord` *must* agree with
64 /// each other. It's easy to accidentally make them disagree by deriving some
65 /// of the traits and manually implementing others.
67 /// An example implementation for a domain in which two books are considered
68 /// the same book if their ISBN matches, even if the formats differ:
79 /// format: BookFormat,
82 /// impl PartialEq for Book {
83 /// fn eq(&self, other: &Self) -> bool {
84 /// self.isbn == other.isbn
88 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
89 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
90 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
92 /// assert!(b1 == b2);
93 /// assert!(b1 != b3);
96 /// ## How can I compare two different types?
98 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
99 /// For example, let's tweak our previous code a bit:
102 /// // The derive implements <BookFormat> == <BookFormat> comparisons
103 /// #[derive(PartialEq)]
104 /// enum BookFormat {
112 /// format: BookFormat,
115 /// // Implement <Book> == <BookFormat> comparisons
116 /// impl PartialEq<BookFormat> for Book {
117 /// fn eq(&self, other: &BookFormat) -> bool {
118 /// self.format == *other
122 /// // Implement <BookFormat> == <Book> comparisons
123 /// impl PartialEq<Book> for BookFormat {
124 /// fn eq(&self, other: &Book) -> bool {
125 /// *self == other.format
129 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
131 /// assert!(b1 == BookFormat::Paperback);
132 /// assert!(BookFormat::Ebook != b1);
135 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
136 /// we allow `BookFormat`s to be compared with `Book`s.
138 /// A comparison like the one above, which ignores some fields of the struct,
139 /// can be dangerous. It can easily lead to an unintended violation of the
140 /// requirements for a partial equivalence relation. For example, if we kept
141 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
142 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
143 /// via the manual implementation from the first example) then the result would
144 /// violate transitivity:
147 /// #[derive(PartialEq)]
148 /// enum BookFormat {
154 /// #[derive(PartialEq)]
157 /// format: BookFormat,
160 /// impl PartialEq<BookFormat> for Book {
161 /// fn eq(&self, other: &BookFormat) -> bool {
162 /// self.format == *other
166 /// impl PartialEq<Book> for BookFormat {
167 /// fn eq(&self, other: &Book) -> bool {
168 /// *self == other.format
173 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
174 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
176 /// assert!(b1 == BookFormat::Paperback);
177 /// assert!(BookFormat::Paperback == b2);
179 /// // The following should hold by transitivity but doesn't.
180 /// assert!(b1 == b2); // <-- PANICS
190 /// assert_eq!(x == y, false);
191 /// assert_eq!(x.eq(&y), false);
194 #[stable(feature = "rust1", since = "1.0.0")]
197 #[rustc_on_unimplemented(
198 message="can't compare `{Self}` with `{Rhs}`",
199 label="no implementation for `{Self} == {Rhs}`",
201 pub trait PartialEq<Rhs: ?Sized = Self> {
202 /// This method tests for `self` and `other` values to be equal, and is used
205 #[stable(feature = "rust1", since = "1.0.0")]
206 fn eq(&self, other: &Rhs) -> bool;
208 /// This method tests for `!=`.
211 #[stable(feature = "rust1", since = "1.0.0")]
212 fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
215 /// Derive macro generating an impl of the trait `PartialEq`.
216 #[rustc_builtin_macro]
217 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
218 #[allow_internal_unstable(core_intrinsics, structural_match)]
219 pub macro PartialEq($item:item) { /* compiler built-in */ }
221 /// Trait for equality comparisons which are [equivalence relations](
222 /// https://en.wikipedia.org/wiki/Equivalence_relation).
224 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
225 /// be (for all `a`, `b` and `c`):
227 /// - reflexive: `a == a`;
228 /// - symmetric: `a == b` implies `b == a`; and
229 /// - transitive: `a == b` and `b == c` implies `a == c`.
231 /// This property cannot be checked by the compiler, and therefore `Eq` implies
232 /// `PartialEq`, and has no extra methods.
236 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
237 /// no extra methods, it is only informing the compiler that this is an
238 /// equivalence relation rather than a partial equivalence relation. Note that
239 /// the `derive` strategy requires all fields are `Eq`, which isn't
242 /// ## How can I implement `Eq`?
244 /// If you cannot use the `derive` strategy, specify that your type implements
245 /// `Eq`, which has no methods:
248 /// enum BookFormat { Paperback, Hardback, Ebook }
251 /// format: BookFormat,
253 /// impl PartialEq for Book {
254 /// fn eq(&self, other: &Self) -> bool {
255 /// self.isbn == other.isbn
258 /// impl Eq for Book {}
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub trait Eq: PartialEq<Self> {
264 // this method is used solely by #[deriving] to assert
265 // that every component of a type implements #[deriving]
266 // itself, the current deriving infrastructure means doing this
267 // assertion without using a method on this trait is nearly
270 // This should never be implemented by hand.
273 #[stable(feature = "rust1", since = "1.0.0")]
274 fn assert_receiver_is_total_eq(&self) {}
277 /// Derive macro generating an impl of the trait `Eq`.
278 #[rustc_builtin_macro]
279 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
280 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match)]
281 pub macro Eq($item:item) { /* compiler built-in */ }
283 // FIXME: this struct is used solely by #[derive] to
284 // assert that every component of a type implements Eq.
286 // This struct should never appear in user code.
288 #[allow(missing_debug_implementations)]
289 #[unstable(feature = "derive_eq",
290 reason = "deriving hack, should not be public",
292 pub struct AssertParamIsEq<T: Eq + ?Sized> { _field: crate::marker::PhantomData<T> }
294 /// An `Ordering` is the result of a comparison between two values.
299 /// use std::cmp::Ordering;
301 /// let result = 1.cmp(&2);
302 /// assert_eq!(Ordering::Less, result);
304 /// let result = 1.cmp(&1);
305 /// assert_eq!(Ordering::Equal, result);
307 /// let result = 2.cmp(&1);
308 /// assert_eq!(Ordering::Greater, result);
310 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
311 #[stable(feature = "rust1", since = "1.0.0")]
313 /// An ordering where a compared value is less than another.
314 #[stable(feature = "rust1", since = "1.0.0")]
316 /// An ordering where a compared value is equal to another.
317 #[stable(feature = "rust1", since = "1.0.0")]
319 /// An ordering where a compared value is greater than another.
320 #[stable(feature = "rust1", since = "1.0.0")]
325 /// Reverses the `Ordering`.
327 /// * `Less` becomes `Greater`.
328 /// * `Greater` becomes `Less`.
329 /// * `Equal` becomes `Equal`.
336 /// use std::cmp::Ordering;
338 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
339 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
340 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
343 /// This method can be used to reverse a comparison:
346 /// let data: &mut [_] = &mut [2, 10, 5, 8];
348 /// // sort the array from largest to smallest.
349 /// data.sort_by(|a, b| a.cmp(b).reverse());
351 /// let b: &mut [_] = &mut [10, 8, 5, 2];
352 /// assert!(data == b);
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn reverse(self) -> Ordering {
364 /// Chains two orderings.
366 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
370 /// use std::cmp::Ordering;
372 /// let result = Ordering::Equal.then(Ordering::Less);
373 /// assert_eq!(result, Ordering::Less);
375 /// let result = Ordering::Less.then(Ordering::Equal);
376 /// assert_eq!(result, Ordering::Less);
378 /// let result = Ordering::Less.then(Ordering::Greater);
379 /// assert_eq!(result, Ordering::Less);
381 /// let result = Ordering::Equal.then(Ordering::Equal);
382 /// assert_eq!(result, Ordering::Equal);
384 /// let x: (i64, i64, i64) = (1, 2, 7);
385 /// let y: (i64, i64, i64) = (1, 5, 3);
386 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
388 /// assert_eq!(result, Ordering::Less);
391 #[stable(feature = "ordering_chaining", since = "1.17.0")]
392 pub fn then(self, other: Ordering) -> Ordering {
399 /// Chains the ordering with the given function.
401 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
407 /// use std::cmp::Ordering;
409 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
410 /// assert_eq!(result, Ordering::Less);
412 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
413 /// assert_eq!(result, Ordering::Less);
415 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
416 /// assert_eq!(result, Ordering::Less);
418 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
419 /// assert_eq!(result, Ordering::Equal);
421 /// let x: (i64, i64, i64) = (1, 2, 7);
422 /// let y: (i64, i64, i64) = (1, 5, 3);
423 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
425 /// assert_eq!(result, Ordering::Less);
428 #[stable(feature = "ordering_chaining", since = "1.17.0")]
429 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
437 /// A helper struct for reverse ordering.
439 /// This struct is a helper to be used with functions like `Vec::sort_by_key` and
440 /// can be used to reverse order a part of a key.
445 /// use std::cmp::Reverse;
447 /// let mut v = vec![1, 2, 3, 4, 5, 6];
448 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
449 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
451 #[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
452 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
453 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
455 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
456 impl<T: PartialOrd> PartialOrd for Reverse<T> {
458 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
459 other.0.partial_cmp(&self.0)
463 fn lt(&self, other: &Self) -> bool { other.0 < self.0 }
465 fn le(&self, other: &Self) -> bool { other.0 <= self.0 }
467 fn gt(&self, other: &Self) -> bool { other.0 > self.0 }
469 fn ge(&self, other: &Self) -> bool { other.0 >= self.0 }
472 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
473 impl<T: Ord> Ord for Reverse<T> {
475 fn cmp(&self, other: &Reverse<T>) -> Ordering {
480 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
482 /// An order is a total order if it is (for all `a`, `b` and `c`):
484 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
485 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
489 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
490 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
491 /// When `derive`d on enums, variants are ordered by their top-to-bottom declaration order.
493 /// ## How can I implement `Ord`?
495 /// `Ord` requires that the type also be `PartialOrd` and `Eq` (which requires `PartialEq`).
497 /// Then you must define an implementation for `cmp()`. You may find it useful to use
498 /// `cmp()` on your type's fields.
500 /// Implementations of `PartialEq`, `PartialOrd`, and `Ord` *must*
501 /// agree with each other. That is, `a.cmp(b) == Ordering::Equal` if
502 /// and only if `a == b` and `Some(a.cmp(b)) == a.partial_cmp(b)` for
503 /// all `a` and `b`. It's easy to accidentally make them disagree by
504 /// deriving some of the traits and manually implementing others.
506 /// Here's an example where you want to sort people by height only, disregarding `id`
510 /// use std::cmp::Ordering;
519 /// impl Ord for Person {
520 /// fn cmp(&self, other: &Self) -> Ordering {
521 /// self.height.cmp(&other.height)
525 /// impl PartialOrd for Person {
526 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
527 /// Some(self.cmp(other))
531 /// impl PartialEq for Person {
532 /// fn eq(&self, other: &Self) -> bool {
533 /// self.height == other.height
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub trait Ord: Eq + PartialOrd<Self> {
544 /// This method returns an `Ordering` between `self` and `other`.
546 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
547 /// `self <operator> other` if true.
552 /// use std::cmp::Ordering;
554 /// assert_eq!(5.cmp(&10), Ordering::Less);
555 /// assert_eq!(10.cmp(&5), Ordering::Greater);
556 /// assert_eq!(5.cmp(&5), Ordering::Equal);
558 #[stable(feature = "rust1", since = "1.0.0")]
559 fn cmp(&self, other: &Self) -> Ordering;
561 /// Compares and returns the maximum of two values.
563 /// Returns the second argument if the comparison determines them to be equal.
568 /// assert_eq!(2, 1.max(2));
569 /// assert_eq!(2, 2.max(2));
571 #[stable(feature = "ord_max_min", since = "1.21.0")]
573 fn max(self, other: Self) -> Self
575 max_by(self, other, Ord::cmp)
578 /// Compares and returns the minimum of two values.
580 /// Returns the first argument if the comparison determines them to be equal.
585 /// assert_eq!(1, 1.min(2));
586 /// assert_eq!(2, 2.min(2));
588 #[stable(feature = "ord_max_min", since = "1.21.0")]
590 fn min(self, other: Self) -> Self
592 min_by(self, other, Ord::cmp)
595 /// Restrict a value to a certain interval.
597 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
598 /// less than `min`. Otherwise this returns `self`.
602 /// Panics if `min > max`.
607 /// #![feature(clamp)]
609 /// assert!((-3).clamp(-2, 1) == -2);
610 /// assert!(0.clamp(-2, 1) == 0);
611 /// assert!(2.clamp(-2, 1) == 1);
613 #[unstable(feature = "clamp", issue = "44095")]
614 fn clamp(self, min: Self, max: Self) -> Self
619 } else if self > max {
627 /// Derive macro generating an impl of the trait `Ord`.
628 #[rustc_builtin_macro]
629 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
630 #[allow_internal_unstable(core_intrinsics)]
631 pub macro Ord($item:item) { /* compiler built-in */ }
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl Eq for Ordering {}
636 #[stable(feature = "rust1", since = "1.0.0")]
637 impl Ord for Ordering {
639 fn cmp(&self, other: &Ordering) -> Ordering {
640 (*self as i32).cmp(&(*other as i32))
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl PartialOrd for Ordering {
647 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
648 (*self as i32).partial_cmp(&(*other as i32))
652 /// Trait for values that can be compared for a sort-order.
654 /// The comparison must satisfy, for all `a`, `b` and `c`:
656 /// - antisymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
657 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
659 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
660 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
665 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
666 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
667 /// When `derive`d on enums, variants are ordered by their top-to-bottom declaration order.
669 /// ## How can I implement `PartialOrd`?
671 /// `PartialOrd` only requires implementation of the `partial_cmp` method, with the others
672 /// generated from default implementations.
674 /// However it remains possible to implement the others separately for types which do not have a
675 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
676 /// false` (cf. IEEE 754-2008 section 5.11).
678 /// `PartialOrd` requires your type to be `PartialEq`.
680 /// Implementations of `PartialEq`, `PartialOrd`, and `Ord` *must* agree with each other. It's
681 /// easy to accidentally make them disagree by deriving some of the traits and manually
682 /// implementing others.
684 /// If your type is `Ord`, you can implement `partial_cmp()` by using `cmp()`:
687 /// use std::cmp::Ordering;
696 /// impl PartialOrd for Person {
697 /// fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
698 /// Some(self.cmp(other))
702 /// impl Ord for Person {
703 /// fn cmp(&self, other: &Person) -> Ordering {
704 /// self.height.cmp(&other.height)
708 /// impl PartialEq for Person {
709 /// fn eq(&self, other: &Person) -> bool {
710 /// self.height == other.height
715 /// You may also find it useful to use `partial_cmp()` on your type's fields. Here
716 /// is an example of `Person` types who have a floating-point `height` field that
717 /// is the only field to be used for sorting:
720 /// use std::cmp::Ordering;
728 /// impl PartialOrd for Person {
729 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
730 /// self.height.partial_cmp(&other.height)
734 /// impl PartialEq for Person {
735 /// fn eq(&self, other: &Self) -> bool {
736 /// self.height == other.height
747 /// assert_eq!(x < y, true);
748 /// assert_eq!(x.lt(&y), true);
750 #[lang = "partial_ord"]
751 #[stable(feature = "rust1", since = "1.0.0")]
756 #[rustc_on_unimplemented(
757 message="can't compare `{Self}` with `{Rhs}`",
758 label="no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
760 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
761 /// This method returns an ordering between `self` and `other` values if one exists.
766 /// use std::cmp::Ordering;
768 /// let result = 1.0.partial_cmp(&2.0);
769 /// assert_eq!(result, Some(Ordering::Less));
771 /// let result = 1.0.partial_cmp(&1.0);
772 /// assert_eq!(result, Some(Ordering::Equal));
774 /// let result = 2.0.partial_cmp(&1.0);
775 /// assert_eq!(result, Some(Ordering::Greater));
778 /// When comparison is impossible:
781 /// let result = std::f64::NAN.partial_cmp(&1.0);
782 /// assert_eq!(result, None);
785 #[stable(feature = "rust1", since = "1.0.0")]
786 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
788 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
793 /// let result = 1.0 < 2.0;
794 /// assert_eq!(result, true);
796 /// let result = 2.0 < 1.0;
797 /// assert_eq!(result, false);
801 #[stable(feature = "rust1", since = "1.0.0")]
802 fn lt(&self, other: &Rhs) -> bool {
803 match self.partial_cmp(other) {
809 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
815 /// let result = 1.0 <= 2.0;
816 /// assert_eq!(result, true);
818 /// let result = 2.0 <= 2.0;
819 /// assert_eq!(result, true);
823 #[stable(feature = "rust1", since = "1.0.0")]
824 fn le(&self, other: &Rhs) -> bool {
825 match self.partial_cmp(other) {
826 Some(Less) | Some(Equal) => true,
831 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
836 /// let result = 1.0 > 2.0;
837 /// assert_eq!(result, false);
839 /// let result = 2.0 > 2.0;
840 /// assert_eq!(result, false);
844 #[stable(feature = "rust1", since = "1.0.0")]
845 fn gt(&self, other: &Rhs) -> bool {
846 match self.partial_cmp(other) {
847 Some(Greater) => true,
852 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
858 /// let result = 2.0 >= 1.0;
859 /// assert_eq!(result, true);
861 /// let result = 2.0 >= 2.0;
862 /// assert_eq!(result, true);
866 #[stable(feature = "rust1", since = "1.0.0")]
867 fn ge(&self, other: &Rhs) -> bool {
868 match self.partial_cmp(other) {
869 Some(Greater) | Some(Equal) => true,
875 /// Derive macro generating an impl of the trait `PartialOrd`.
876 #[rustc_builtin_macro]
877 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
878 #[allow_internal_unstable(core_intrinsics)]
879 pub macro PartialOrd($item:item) { /* compiler built-in */ }
881 /// Compares and returns the minimum of two values.
883 /// Returns the first argument if the comparison determines them to be equal.
885 /// Internally uses an alias to `Ord::min`.
892 /// assert_eq!(1, cmp::min(1, 2));
893 /// assert_eq!(2, cmp::min(2, 2));
896 #[stable(feature = "rust1", since = "1.0.0")]
897 pub fn min<T: Ord>(v1: T, v2: T) -> T {
901 /// Returns the minimum of two values with respect to the specified comparison function.
903 /// Returns the first argument if the comparison determines them to be equal.
908 /// #![feature(cmp_min_max_by)]
912 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
913 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
916 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
917 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
918 match compare(&v1, &v2) {
919 Ordering::Less | Ordering::Equal => v1,
920 Ordering::Greater => v2,
924 /// Returns the element that gives the minimum value from the specified function.
926 /// Returns the first argument if the comparison determines them to be equal.
931 /// #![feature(cmp_min_max_by)]
935 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
936 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
939 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
940 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
941 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
944 /// Compares and returns the maximum of two values.
946 /// Returns the second argument if the comparison determines them to be equal.
948 /// Internally uses an alias to `Ord::max`.
955 /// assert_eq!(2, cmp::max(1, 2));
956 /// assert_eq!(2, cmp::max(2, 2));
959 #[stable(feature = "rust1", since = "1.0.0")]
960 pub fn max<T: Ord>(v1: T, v2: T) -> T {
964 /// Returns the maximum of two values with respect to the specified comparison function.
966 /// Returns the second argument if the comparison determines them to be equal.
971 /// #![feature(cmp_min_max_by)]
975 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
976 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
979 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
980 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
981 match compare(&v1, &v2) {
982 Ordering::Less | Ordering::Equal => v2,
983 Ordering::Greater => v1,
987 /// Returns the element that gives the maximum value from the specified function.
989 /// Returns the second argument if the comparison determines them to be equal.
994 /// #![feature(cmp_min_max_by)]
998 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
999 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1002 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1003 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1004 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1007 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1009 use crate::hint::unreachable_unchecked;
1010 use crate::cmp::Ordering::{self, Less, Greater, Equal};
1012 macro_rules! partial_eq_impl {
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl PartialEq for $t {
1017 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1019 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl PartialEq for () {
1027 fn eq(&self, _other: &()) -> bool { true }
1029 fn ne(&self, _other: &()) -> bool { false }
1033 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1036 macro_rules! eq_impl {
1038 #[stable(feature = "rust1", since = "1.0.0")]
1043 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1045 macro_rules! partial_ord_impl {
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 impl PartialOrd for $t {
1050 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1051 match (self <= other, self >= other) {
1052 (false, false) => None,
1053 (false, true) => Some(Greater),
1054 (true, false) => Some(Less),
1055 (true, true) => Some(Equal),
1059 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1061 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1063 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1065 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl PartialOrd for () {
1073 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl PartialOrd for bool {
1081 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1082 (*self as u8).partial_cmp(&(*other as u8))
1086 partial_ord_impl! { f32 f64 }
1088 macro_rules! ord_impl {
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl PartialOrd for $t {
1093 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1094 Some(self.cmp(other))
1097 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1099 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1101 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1103 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1106 #[stable(feature = "rust1", since = "1.0.0")]
1109 fn cmp(&self, other: &$t) -> Ordering {
1110 // The order here is important to generate more optimal assembly.
1111 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1112 if *self < *other { Less }
1113 else if *self == *other { Equal }
1120 #[stable(feature = "rust1", since = "1.0.0")]
1123 fn cmp(&self, _other: &()) -> Ordering { Equal }
1126 #[stable(feature = "rust1", since = "1.0.0")]
1129 fn cmp(&self, other: &bool) -> Ordering {
1130 // Casting to i8's and converting the difference to an Ordering generates
1131 // more optimal assembly.
1132 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1133 match (*self as i8) - (*other as i8) {
1137 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1138 _ => unsafe { unreachable_unchecked() },
1143 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1145 #[stable(feature = "never_type", since = "1.41.0")]
1146 impl PartialEq for ! {
1147 fn eq(&self, _: &!) -> bool {
1152 #[stable(feature = "never_type", since = "1.41.0")]
1155 #[stable(feature = "never_type", since = "1.41.0")]
1156 impl PartialOrd for ! {
1157 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1162 #[stable(feature = "never_type", since = "1.41.0")]
1164 fn cmp(&self, _: &!) -> Ordering {
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A where A: PartialEq<B> {
1174 fn eq(&self, other: & &B) -> bool { PartialEq::eq(*self, *other) }
1176 fn ne(&self, other: & &B) -> bool { PartialEq::ne(*self, *other) }
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A where A: PartialOrd<B> {
1181 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1182 PartialOrd::partial_cmp(*self, *other)
1185 fn lt(&self, other: & &B) -> bool { PartialOrd::lt(*self, *other) }
1187 fn le(&self, other: & &B) -> bool { PartialOrd::le(*self, *other) }
1189 fn gt(&self, other: & &B) -> bool { PartialOrd::gt(*self, *other) }
1191 fn ge(&self, other: & &B) -> bool { PartialOrd::ge(*self, *other) }
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<A: ?Sized> Ord for &A where A: Ord {
1196 fn cmp(&self, other: &Self) -> Ordering { Ord::cmp(*self, *other) }
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 impl<A: ?Sized> Eq for &A where A: Eq {}
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A where A: PartialEq<B> {
1206 fn eq(&self, other: &&mut B) -> bool { PartialEq::eq(*self, *other) }
1208 fn ne(&self, other: &&mut B) -> bool { PartialEq::ne(*self, *other) }
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A where A: PartialOrd<B> {
1213 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1214 PartialOrd::partial_cmp(*self, *other)
1217 fn lt(&self, other: &&mut B) -> bool { PartialOrd::lt(*self, *other) }
1219 fn le(&self, other: &&mut B) -> bool { PartialOrd::le(*self, *other) }
1221 fn gt(&self, other: &&mut B) -> bool { PartialOrd::gt(*self, *other) }
1223 fn ge(&self, other: &&mut B) -> bool { PartialOrd::ge(*self, *other) }
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl<A: ?Sized> Ord for &mut A where A: Ord {
1228 fn cmp(&self, other: &Self) -> Ordering { Ord::cmp(*self, *other) }
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A where A: PartialEq<B> {
1236 fn eq(&self, other: &&mut B) -> bool { PartialEq::eq(*self, *other) }
1238 fn ne(&self, other: &&mut B) -> bool { PartialEq::ne(*self, *other) }
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A where A: PartialEq<B> {
1244 fn eq(&self, other: &&B) -> bool { PartialEq::eq(*self, *other) }
1246 fn ne(&self, other: &&B) -> bool { PartialEq::ne(*self, *other) }