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 /// You can also combine these implementations to let the `==` operator work with
139 /// two different types:
142 /// #[derive(PartialEq)]
143 /// enum BookFormat {
151 /// format: BookFormat,
154 /// impl PartialEq<BookFormat> for Book {
155 /// fn eq(&self, other: &BookFormat) -> bool {
156 /// self.format == *other
160 /// impl PartialEq<Book> for BookFormat {
161 /// fn eq(&self, other: &Book) -> bool {
162 /// *self == other.format
166 /// impl PartialEq for Book {
167 /// fn eq(&self, other: &Book) -> bool {
168 /// self.isbn == other.isbn
172 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
173 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
175 /// assert!(b1 == BookFormat::Paperback);
176 /// assert!(BookFormat::Ebook != b1);
177 /// assert!(b1 == b2);
186 /// assert_eq!(x == y, false);
187 /// assert_eq!(x.eq(&y), false);
190 #[stable(feature = "rust1", since = "1.0.0")]
193 #[rustc_on_unimplemented(
194 message="can't compare `{Self}` with `{Rhs}`",
195 label="no implementation for `{Self} == {Rhs}`",
197 pub trait PartialEq<Rhs: ?Sized = Self> {
198 /// This method tests for `self` and `other` values to be equal, and is used
201 #[stable(feature = "rust1", since = "1.0.0")]
202 fn eq(&self, other: &Rhs) -> bool;
204 /// This method tests for `!=`.
207 #[stable(feature = "rust1", since = "1.0.0")]
208 fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
211 /// Derive macro generating an impl of the trait `PartialEq`.
212 #[rustc_builtin_macro]
213 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
214 #[allow_internal_unstable(core_intrinsics)]
215 pub macro PartialEq($item:item) { /* compiler built-in */ }
217 /// Trait for equality comparisons which are [equivalence relations](
218 /// https://en.wikipedia.org/wiki/Equivalence_relation).
220 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
221 /// be (for all `a`, `b` and `c`):
223 /// - reflexive: `a == a`;
224 /// - symmetric: `a == b` implies `b == a`; and
225 /// - transitive: `a == b` and `b == c` implies `a == c`.
227 /// This property cannot be checked by the compiler, and therefore `Eq` implies
228 /// `PartialEq`, and has no extra methods.
232 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
233 /// no extra methods, it is only informing the compiler that this is an
234 /// equivalence relation rather than a partial equivalence relation. Note that
235 /// the `derive` strategy requires all fields are `Eq`, which isn't
238 /// ## How can I implement `Eq`?
240 /// If you cannot use the `derive` strategy, specify that your type implements
241 /// `Eq`, which has no methods:
244 /// enum BookFormat { Paperback, Hardback, Ebook }
247 /// format: BookFormat,
249 /// impl PartialEq for Book {
250 /// fn eq(&self, other: &Self) -> bool {
251 /// self.isbn == other.isbn
254 /// impl Eq for Book {}
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub trait Eq: PartialEq<Self> {
260 // this method is used solely by #[deriving] to assert
261 // that every component of a type implements #[deriving]
262 // itself, the current deriving infrastructure means doing this
263 // assertion without using a method on this trait is nearly
266 // This should never be implemented by hand.
269 #[stable(feature = "rust1", since = "1.0.0")]
270 fn assert_receiver_is_total_eq(&self) {}
273 /// Derive macro generating an impl of the trait `Eq`.
274 #[rustc_builtin_macro]
275 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
276 #[allow_internal_unstable(core_intrinsics, derive_eq)]
277 pub macro Eq($item:item) { /* compiler built-in */ }
279 // FIXME: this struct is used solely by #[derive] to
280 // assert that every component of a type implements Eq.
282 // This struct should never appear in user code.
284 #[allow(missing_debug_implementations)]
285 #[unstable(feature = "derive_eq",
286 reason = "deriving hack, should not be public",
288 pub struct AssertParamIsEq<T: Eq + ?Sized> { _field: crate::marker::PhantomData<T> }
290 /// An `Ordering` is the result of a comparison between two values.
295 /// use std::cmp::Ordering;
297 /// let result = 1.cmp(&2);
298 /// assert_eq!(Ordering::Less, result);
300 /// let result = 1.cmp(&1);
301 /// assert_eq!(Ordering::Equal, result);
303 /// let result = 2.cmp(&1);
304 /// assert_eq!(Ordering::Greater, result);
306 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
307 #[stable(feature = "rust1", since = "1.0.0")]
309 /// An ordering where a compared value is less than another.
310 #[stable(feature = "rust1", since = "1.0.0")]
312 /// An ordering where a compared value is equal to another.
313 #[stable(feature = "rust1", since = "1.0.0")]
315 /// An ordering where a compared value is greater than another.
316 #[stable(feature = "rust1", since = "1.0.0")]
321 /// Reverses the `Ordering`.
323 /// * `Less` becomes `Greater`.
324 /// * `Greater` becomes `Less`.
325 /// * `Equal` becomes `Equal`.
332 /// use std::cmp::Ordering;
334 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
335 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
336 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
339 /// This method can be used to reverse a comparison:
342 /// let data: &mut [_] = &mut [2, 10, 5, 8];
344 /// // sort the array from largest to smallest.
345 /// data.sort_by(|a, b| a.cmp(b).reverse());
347 /// let b: &mut [_] = &mut [10, 8, 5, 2];
348 /// assert!(data == b);
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn reverse(self) -> Ordering {
360 /// Chains two orderings.
362 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
366 /// use std::cmp::Ordering;
368 /// let result = Ordering::Equal.then(Ordering::Less);
369 /// assert_eq!(result, Ordering::Less);
371 /// let result = Ordering::Less.then(Ordering::Equal);
372 /// assert_eq!(result, Ordering::Less);
374 /// let result = Ordering::Less.then(Ordering::Greater);
375 /// assert_eq!(result, Ordering::Less);
377 /// let result = Ordering::Equal.then(Ordering::Equal);
378 /// assert_eq!(result, Ordering::Equal);
380 /// let x: (i64, i64, i64) = (1, 2, 7);
381 /// let y: (i64, i64, i64) = (1, 5, 3);
382 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
384 /// assert_eq!(result, Ordering::Less);
387 #[stable(feature = "ordering_chaining", since = "1.17.0")]
388 pub fn then(self, other: Ordering) -> Ordering {
395 /// Chains the ordering with the given function.
397 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
403 /// use std::cmp::Ordering;
405 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
406 /// assert_eq!(result, Ordering::Less);
408 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
409 /// assert_eq!(result, Ordering::Less);
411 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
412 /// assert_eq!(result, Ordering::Less);
414 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
415 /// assert_eq!(result, Ordering::Equal);
417 /// let x: (i64, i64, i64) = (1, 2, 7);
418 /// let y: (i64, i64, i64) = (1, 5, 3);
419 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
421 /// assert_eq!(result, Ordering::Less);
424 #[stable(feature = "ordering_chaining", since = "1.17.0")]
425 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
433 /// A helper struct for reverse ordering.
435 /// This struct is a helper to be used with functions like `Vec::sort_by_key` and
436 /// can be used to reverse order a part of a key.
441 /// use std::cmp::Reverse;
443 /// let mut v = vec![1, 2, 3, 4, 5, 6];
444 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
445 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
447 #[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
448 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
449 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
451 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
452 impl<T: PartialOrd> PartialOrd for Reverse<T> {
454 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
455 other.0.partial_cmp(&self.0)
459 fn lt(&self, other: &Self) -> bool { other.0 < self.0 }
461 fn le(&self, other: &Self) -> bool { other.0 <= self.0 }
463 fn ge(&self, other: &Self) -> bool { other.0 >= self.0 }
465 fn gt(&self, other: &Self) -> bool { other.0 > self.0 }
468 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
469 impl<T: Ord> Ord for Reverse<T> {
471 fn cmp(&self, other: &Reverse<T>) -> Ordering {
476 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
478 /// An order is a total order if it is (for all `a`, `b` and `c`):
480 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
481 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
485 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
486 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
487 /// When `derive`d on enums, variants are ordered by their top-to-bottom declaration order.
489 /// ## How can I implement `Ord`?
491 /// `Ord` requires that the type also be `PartialOrd` and `Eq` (which requires `PartialEq`).
493 /// Then you must define an implementation for `cmp()`. You may find it useful to use
494 /// `cmp()` on your type's fields.
496 /// Implementations of `PartialEq`, `PartialOrd`, and `Ord` *must*
497 /// agree with each other. That is, `a.cmp(b) == Ordering::Equal` if
498 /// and only if `a == b` and `Some(a.cmp(b)) == a.partial_cmp(b)` for
499 /// all `a` and `b`. It's easy to accidentally make them disagree by
500 /// deriving some of the traits and manually implementing others.
502 /// Here's an example where you want to sort people by height only, disregarding `id`
506 /// use std::cmp::Ordering;
515 /// impl Ord for Person {
516 /// fn cmp(&self, other: &Self) -> Ordering {
517 /// self.height.cmp(&other.height)
521 /// impl PartialOrd for Person {
522 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
523 /// Some(self.cmp(other))
527 /// impl PartialEq for Person {
528 /// fn eq(&self, other: &Self) -> bool {
529 /// self.height == other.height
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub trait Ord: Eq + PartialOrd<Self> {
540 /// This method returns an `Ordering` between `self` and `other`.
542 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
543 /// `self <operator> other` if true.
548 /// use std::cmp::Ordering;
550 /// assert_eq!(5.cmp(&10), Ordering::Less);
551 /// assert_eq!(10.cmp(&5), Ordering::Greater);
552 /// assert_eq!(5.cmp(&5), Ordering::Equal);
554 #[stable(feature = "rust1", since = "1.0.0")]
555 fn cmp(&self, other: &Self) -> Ordering;
557 /// Compares and returns the maximum of two values.
559 /// Returns the second argument if the comparison determines them to be equal.
564 /// assert_eq!(2, 1.max(2));
565 /// assert_eq!(2, 2.max(2));
567 #[stable(feature = "ord_max_min", since = "1.21.0")]
569 fn max(self, other: Self) -> Self
571 max_by(self, other, Ord::cmp)
574 /// Compares and returns the minimum of two values.
576 /// Returns the first argument if the comparison determines them to be equal.
581 /// assert_eq!(1, 1.min(2));
582 /// assert_eq!(2, 2.min(2));
584 #[stable(feature = "ord_max_min", since = "1.21.0")]
586 fn min(self, other: Self) -> Self
588 min_by(self, other, Ord::cmp)
591 /// Restrict a value to a certain interval.
593 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
594 /// less than `min`. Otherwise this returns `self`.
598 /// Panics if `min > max`.
603 /// #![feature(clamp)]
605 /// assert!((-3).clamp(-2, 1) == -2);
606 /// assert!(0.clamp(-2, 1) == 0);
607 /// assert!(2.clamp(-2, 1) == 1);
609 #[unstable(feature = "clamp", issue = "44095")]
610 fn clamp(self, min: Self, max: Self) -> Self
615 } else if self > max {
623 /// Derive macro generating an impl of the trait `Ord`.
624 #[rustc_builtin_macro]
625 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
626 #[allow_internal_unstable(core_intrinsics)]
627 pub macro Ord($item:item) { /* compiler built-in */ }
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl Eq for Ordering {}
632 #[stable(feature = "rust1", since = "1.0.0")]
633 impl Ord for Ordering {
635 fn cmp(&self, other: &Ordering) -> Ordering {
636 (*self as i32).cmp(&(*other as i32))
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl PartialOrd for Ordering {
643 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
644 (*self as i32).partial_cmp(&(*other as i32))
648 /// Trait for values that can be compared for a sort-order.
650 /// The comparison must satisfy, for all `a`, `b` and `c`:
652 /// - antisymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
653 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
655 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
656 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
661 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
662 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
663 /// When `derive`d on enums, variants are ordered by their top-to-bottom declaration order.
665 /// ## How can I implement `PartialOrd`?
667 /// `PartialOrd` only requires implementation of the `partial_cmp` method, with the others
668 /// generated from default implementations.
670 /// However it remains possible to implement the others separately for types which do not have a
671 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
672 /// false` (cf. IEEE 754-2008 section 5.11).
674 /// `PartialOrd` requires your type to be `PartialEq`.
676 /// Implementations of `PartialEq`, `PartialOrd`, and `Ord` *must* agree with each other. It's
677 /// easy to accidentally make them disagree by deriving some of the traits and manually
678 /// implementing others.
680 /// If your type is `Ord`, you can implement `partial_cmp()` by using `cmp()`:
683 /// use std::cmp::Ordering;
692 /// impl PartialOrd for Person {
693 /// fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
694 /// Some(self.cmp(other))
698 /// impl Ord for Person {
699 /// fn cmp(&self, other: &Person) -> Ordering {
700 /// self.height.cmp(&other.height)
704 /// impl PartialEq for Person {
705 /// fn eq(&self, other: &Person) -> bool {
706 /// self.height == other.height
711 /// You may also find it useful to use `partial_cmp()` on your type's fields. Here
712 /// is an example of `Person` types who have a floating-point `height` field that
713 /// is the only field to be used for sorting:
716 /// use std::cmp::Ordering;
724 /// impl PartialOrd for Person {
725 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
726 /// self.height.partial_cmp(&other.height)
730 /// impl PartialEq for Person {
731 /// fn eq(&self, other: &Self) -> bool {
732 /// self.height == other.height
743 /// assert_eq!(x < y, true);
744 /// assert_eq!(x.lt(&y), true);
746 #[lang = "partial_ord"]
747 #[stable(feature = "rust1", since = "1.0.0")]
752 #[rustc_on_unimplemented(
753 message="can't compare `{Self}` with `{Rhs}`",
754 label="no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
756 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
757 /// This method returns an ordering between `self` and `other` values if one exists.
762 /// use std::cmp::Ordering;
764 /// let result = 1.0.partial_cmp(&2.0);
765 /// assert_eq!(result, Some(Ordering::Less));
767 /// let result = 1.0.partial_cmp(&1.0);
768 /// assert_eq!(result, Some(Ordering::Equal));
770 /// let result = 2.0.partial_cmp(&1.0);
771 /// assert_eq!(result, Some(Ordering::Greater));
774 /// When comparison is impossible:
777 /// let result = std::f64::NAN.partial_cmp(&1.0);
778 /// assert_eq!(result, None);
781 #[stable(feature = "rust1", since = "1.0.0")]
782 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
784 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
789 /// let result = 1.0 < 2.0;
790 /// assert_eq!(result, true);
792 /// let result = 2.0 < 1.0;
793 /// assert_eq!(result, false);
797 #[stable(feature = "rust1", since = "1.0.0")]
798 fn lt(&self, other: &Rhs) -> bool {
799 match self.partial_cmp(other) {
805 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
811 /// let result = 1.0 <= 2.0;
812 /// assert_eq!(result, true);
814 /// let result = 2.0 <= 2.0;
815 /// assert_eq!(result, true);
819 #[stable(feature = "rust1", since = "1.0.0")]
820 fn le(&self, other: &Rhs) -> bool {
821 match self.partial_cmp(other) {
822 Some(Less) | Some(Equal) => true,
827 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
832 /// let result = 1.0 > 2.0;
833 /// assert_eq!(result, false);
835 /// let result = 2.0 > 2.0;
836 /// assert_eq!(result, false);
840 #[stable(feature = "rust1", since = "1.0.0")]
841 fn gt(&self, other: &Rhs) -> bool {
842 match self.partial_cmp(other) {
843 Some(Greater) => true,
848 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
854 /// let result = 2.0 >= 1.0;
855 /// assert_eq!(result, true);
857 /// let result = 2.0 >= 2.0;
858 /// assert_eq!(result, true);
862 #[stable(feature = "rust1", since = "1.0.0")]
863 fn ge(&self, other: &Rhs) -> bool {
864 match self.partial_cmp(other) {
865 Some(Greater) | Some(Equal) => true,
871 /// Derive macro generating an impl of the trait `PartialOrd`.
872 #[rustc_builtin_macro]
873 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
874 #[allow_internal_unstable(core_intrinsics)]
875 pub macro PartialOrd($item:item) { /* compiler built-in */ }
877 /// Compares and returns the minimum of two values.
879 /// Returns the first argument if the comparison determines them to be equal.
881 /// Internally uses an alias to `Ord::min`.
888 /// assert_eq!(1, cmp::min(1, 2));
889 /// assert_eq!(2, cmp::min(2, 2));
892 #[stable(feature = "rust1", since = "1.0.0")]
893 pub fn min<T: Ord>(v1: T, v2: T) -> T {
897 /// Returns the minimum of two values with respect to the specified comparison function.
899 /// Returns the first argument if the comparison determines them to be equal.
904 /// #![feature(cmp_min_max_by)]
908 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
909 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
912 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
913 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
914 match compare(&v1, &v2) {
915 Ordering::Less | Ordering::Equal => v1,
916 Ordering::Greater => v2,
920 /// Returns the element that gives the minimum value from the specified function.
922 /// Returns the first argument if the comparison determines them to be equal.
927 /// #![feature(cmp_min_max_by)]
931 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
932 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
935 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
936 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
937 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
940 /// Compares and returns the maximum of two values.
942 /// Returns the second argument if the comparison determines them to be equal.
944 /// Internally uses an alias to `Ord::max`.
951 /// assert_eq!(2, cmp::max(1, 2));
952 /// assert_eq!(2, cmp::max(2, 2));
955 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn max<T: Ord>(v1: T, v2: T) -> T {
960 /// Returns the maximum of two values with respect to the specified comparison function.
962 /// Returns the second argument if the comparison determines them to be equal.
967 /// #![feature(cmp_min_max_by)]
971 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
972 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
975 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
976 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
977 match compare(&v1, &v2) {
978 Ordering::Less | Ordering::Equal => v2,
979 Ordering::Greater => v1,
983 /// Returns the element that gives the maximum value from the specified function.
985 /// Returns the second argument if the comparison determines them to be equal.
990 /// #![feature(cmp_min_max_by)]
994 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
995 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
998 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
999 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1000 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1003 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1005 use crate::cmp::Ordering::{self, Less, Greater, Equal};
1007 macro_rules! partial_eq_impl {
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 impl PartialEq for $t {
1012 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1014 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 impl PartialEq for () {
1022 fn eq(&self, _other: &()) -> bool { true }
1024 fn ne(&self, _other: &()) -> bool { false }
1028 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1031 macro_rules! eq_impl {
1033 #[stable(feature = "rust1", since = "1.0.0")]
1038 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1040 macro_rules! partial_ord_impl {
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl PartialOrd for $t {
1045 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1046 match (self <= other, self >= other) {
1047 (false, false) => None,
1048 (false, true) => Some(Greater),
1049 (true, false) => Some(Less),
1050 (true, true) => Some(Equal),
1054 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1056 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1058 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1060 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 impl PartialOrd for () {
1068 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl PartialOrd for bool {
1076 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1077 (*self as u8).partial_cmp(&(*other as u8))
1081 partial_ord_impl! { f32 f64 }
1083 macro_rules! ord_impl {
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl PartialOrd for $t {
1088 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1089 Some(self.cmp(other))
1092 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1094 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1096 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1098 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1101 #[stable(feature = "rust1", since = "1.0.0")]
1104 fn cmp(&self, other: &$t) -> Ordering {
1105 // The order here is important to generate more optimal assembly.
1106 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1107 if *self < *other { Less }
1108 else if *self == *other { Equal }
1115 #[stable(feature = "rust1", since = "1.0.0")]
1118 fn cmp(&self, _other: &()) -> Ordering { Equal }
1121 #[stable(feature = "rust1", since = "1.0.0")]
1124 fn cmp(&self, other: &bool) -> Ordering {
1125 (*self as u8).cmp(&(*other as u8))
1129 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1131 #[unstable(feature = "never_type", issue = "35121")]
1132 impl PartialEq for ! {
1133 fn eq(&self, _: &!) -> bool {
1138 #[unstable(feature = "never_type", issue = "35121")]
1141 #[unstable(feature = "never_type", issue = "35121")]
1142 impl PartialOrd for ! {
1143 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1148 #[unstable(feature = "never_type", issue = "35121")]
1150 fn cmp(&self, _: &!) -> Ordering {
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A where A: PartialEq<B> {
1160 fn eq(&self, other: & &B) -> bool { PartialEq::eq(*self, *other) }
1162 fn ne(&self, other: & &B) -> bool { PartialEq::ne(*self, *other) }
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A where A: PartialOrd<B> {
1167 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1168 PartialOrd::partial_cmp(*self, *other)
1171 fn lt(&self, other: & &B) -> bool { PartialOrd::lt(*self, *other) }
1173 fn le(&self, other: & &B) -> bool { PartialOrd::le(*self, *other) }
1175 fn ge(&self, other: & &B) -> bool { PartialOrd::ge(*self, *other) }
1177 fn gt(&self, other: & &B) -> bool { PartialOrd::gt(*self, *other) }
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 impl<A: ?Sized> Ord for &A where A: Ord {
1182 fn cmp(&self, other: &Self) -> Ordering { Ord::cmp(*self, *other) }
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl<A: ?Sized> Eq for &A where A: Eq {}
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A where A: PartialEq<B> {
1192 fn eq(&self, other: &&mut B) -> bool { PartialEq::eq(*self, *other) }
1194 fn ne(&self, other: &&mut B) -> bool { PartialEq::ne(*self, *other) }
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A where A: PartialOrd<B> {
1199 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1200 PartialOrd::partial_cmp(*self, *other)
1203 fn lt(&self, other: &&mut B) -> bool { PartialOrd::lt(*self, *other) }
1205 fn le(&self, other: &&mut B) -> bool { PartialOrd::le(*self, *other) }
1207 fn ge(&self, other: &&mut B) -> bool { PartialOrd::ge(*self, *other) }
1209 fn gt(&self, other: &&mut B) -> bool { PartialOrd::gt(*self, *other) }
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 impl<A: ?Sized> Ord for &mut A where A: Ord {
1214 fn cmp(&self, other: &Self) -> Ordering { Ord::cmp(*self, *other) }
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A where A: PartialEq<B> {
1222 fn eq(&self, other: &&mut B) -> bool { PartialEq::eq(*self, *other) }
1224 fn ne(&self, other: &&mut B) -> bool { PartialEq::ne(*self, *other) }
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A where A: PartialEq<B> {
1230 fn eq(&self, other: &&B) -> bool { PartialEq::eq(*self, *other) }
1232 fn ne(&self, other: &&B) -> bool { PartialEq::ne(*self, *other) }