1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Functionality for ordering and comparison.
13 //! This module defines both `PartialOrd` and `PartialEq` traits which are used
14 //! by the compiler to implement comparison operators. Rust programs may
15 //! implement `PartialOrd` to overload the `<`, `<=`, `>`, and `>=` operators,
16 //! and may implement `PartialEq` to overload the `==` and `!=` operators.
24 //! // these two lines are equivalent
25 //! assert_eq!(x < y, true);
26 //! assert_eq!(x.lt(&y), true);
28 //! // these two lines are also equivalent
29 //! assert_eq!(x == y, false);
30 //! assert_eq!(x.eq(&y), false);
33 #![stable(feature = "rust1", since = "1.0.0")]
35 use self::Ordering::*;
37 /// Trait for equality comparisons which are [partial equivalence
38 /// relations](http://en.wikipedia.org/wiki/Partial_equivalence_relation).
40 /// This trait allows for partial equality, for types that do not have a full
41 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
42 /// so floating point types implement `PartialEq` but not `Eq`.
44 /// Formally, the equality must be (for all `a`, `b` and `c`):
46 /// - symmetric: `a == b` implies `b == a`; and
47 /// - transitive: `a == b` and `b == c` implies `a == c`.
49 /// Note that these requirements mean that the trait itself must be implemented
50 /// symmetrically and transitively: if `T: PartialEq<U>` and `U: PartialEq<V>`
51 /// then `U: PartialEq<T>` and `T: PartialEq<V>`.
55 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
56 /// instances are equal if all fields are equal, and not equal if any fields
57 /// are not equal. When `derive`d on enums, each variant is equal to itself
58 /// and not equal to the other variants.
60 /// ## How can I implement `PartialEq`?
62 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined
63 /// in terms of it by default. Any manual implementation of `ne` *must* respect
64 /// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
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:
71 /// enum BookFormat { Paperback, Hardback, Ebook }
74 /// format: BookFormat,
77 /// impl PartialEq for Book {
78 /// fn eq(&self, other: &Book) -> bool {
79 /// self.isbn == other.isbn
83 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
84 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
85 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
87 /// assert!(b1 == b2);
88 /// assert!(b1 != b3);
97 /// assert_eq!(x == y, false);
98 /// assert_eq!(x.eq(&y), false);
101 #[stable(feature = "rust1", since = "1.0.0")]
102 pub trait PartialEq<Rhs: ?Sized = Self> {
103 /// This method tests for `self` and `other` values to be equal, and is used
105 #[stable(feature = "rust1", since = "1.0.0")]
106 fn eq(&self, other: &Rhs) -> bool;
108 /// This method tests for `!=`.
110 #[stable(feature = "rust1", since = "1.0.0")]
111 fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
114 /// Trait for equality comparisons which are [equivalence relations](
115 /// https://en.wikipedia.org/wiki/Equivalence_relation).
117 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
118 /// be (for all `a`, `b` and `c`):
120 /// - reflexive: `a == a`;
121 /// - symmetric: `a == b` implies `b == a`; and
122 /// - transitive: `a == b` and `b == c` implies `a == c`.
124 /// This property cannot be checked by the compiler, and therefore `Eq` implies
125 /// `PartialEq`, and has no extra methods.
129 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
130 /// no extra methods, it is only informing the compiler that this is an
131 /// equivalence relation rather than a partial equivalence relation. Note that
132 /// the `derive` strategy requires all fields are `PartialEq`, which isn't
135 /// ## How can I implement `Eq`?
137 /// If you cannot use the `derive` strategy, specify that your type implements
138 /// `Eq`, which has no methods:
141 /// enum BookFormat { Paperback, Hardback, Ebook }
144 /// format: BookFormat,
146 /// impl PartialEq for Book {
147 /// fn eq(&self, other: &Book) -> bool {
148 /// self.isbn == other.isbn
151 /// impl Eq for Book {}
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub trait Eq: PartialEq<Self> {
155 // FIXME #13101: this method is used solely by #[deriving] to
156 // assert that every component of a type implements #[deriving]
157 // itself, the current deriving infrastructure means doing this
158 // assertion without using a method on this trait is nearly
161 // This should never be implemented by hand.
164 #[stable(feature = "rust1", since = "1.0.0")]
165 fn assert_receiver_is_total_eq(&self) {}
168 /// An `Ordering` is the result of a comparison between two values.
173 /// use std::cmp::Ordering;
175 /// let result = 1.cmp(&2);
176 /// assert_eq!(Ordering::Less, result);
178 /// let result = 1.cmp(&1);
179 /// assert_eq!(Ordering::Equal, result);
181 /// let result = 2.cmp(&1);
182 /// assert_eq!(Ordering::Greater, result);
184 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
185 #[stable(feature = "rust1", since = "1.0.0")]
187 /// An ordering where a compared value is less [than another].
188 #[stable(feature = "rust1", since = "1.0.0")]
190 /// An ordering where a compared value is equal [to another].
191 #[stable(feature = "rust1", since = "1.0.0")]
193 /// An ordering where a compared value is greater [than another].
194 #[stable(feature = "rust1", since = "1.0.0")]
199 /// Reverse the `Ordering`.
201 /// * `Less` becomes `Greater`.
202 /// * `Greater` becomes `Less`.
203 /// * `Equal` becomes `Equal`.
210 /// use std::cmp::Ordering;
212 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
213 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
214 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
217 /// This method can be used to reverse a comparison:
220 /// let mut data: &mut [_] = &mut [2, 10, 5, 8];
222 /// // sort the array from largest to smallest.
223 /// data.sort_by(|a, b| a.cmp(b).reverse());
225 /// let b: &mut [_] = &mut [10, 8, 5, 2];
226 /// assert!(data == b);
229 #[stable(feature = "rust1", since = "1.0.0")]
230 pub fn reverse(self) -> Ordering {
239 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
241 /// An order is a total order if it is (for all `a`, `b` and `c`):
243 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
244 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
248 /// This trait can be used with `#[derive]`. When `derive`d, it will produce a lexicographic
249 /// ordering based on the top-to-bottom declaration order of the struct's members.
251 /// ## How can I implement `Ord`?
253 /// `Ord` requires that the type also be `PartialOrd` and `Eq` (which requires `PartialEq`).
255 /// Then you must define an implementation for `cmp()`. You may find it useful to use
256 /// `cmp()` on your type's fields.
258 /// Here's an example where you want to sort people by height only, disregarding `id`
262 /// use std::cmp::Ordering;
271 /// impl Ord for Person {
272 /// fn cmp(&self, other: &Person) -> Ordering {
273 /// self.height.cmp(&other.height)
277 /// impl PartialOrd for Person {
278 /// fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
279 /// Some(self.cmp(other))
283 /// impl PartialEq for Person {
284 /// fn eq(&self, other: &Person) -> bool {
285 /// self.height == other.height
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub trait Ord: Eq + PartialOrd<Self> {
291 /// This method returns an `Ordering` between `self` and `other`.
293 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
294 /// `self <operator> other` if true.
299 /// use std::cmp::Ordering;
301 /// assert_eq!(5.cmp(&10), Ordering::Less);
302 /// assert_eq!(10.cmp(&5), Ordering::Greater);
303 /// assert_eq!(5.cmp(&5), Ordering::Equal);
305 #[stable(feature = "rust1", since = "1.0.0")]
306 fn cmp(&self, other: &Self) -> Ordering;
309 #[stable(feature = "rust1", since = "1.0.0")]
310 impl Eq for Ordering {}
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl Ord for Ordering {
315 fn cmp(&self, other: &Ordering) -> Ordering {
316 (*self as i32).cmp(&(*other as i32))
320 #[stable(feature = "rust1", since = "1.0.0")]
321 impl PartialOrd for Ordering {
323 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
324 (*self as i32).partial_cmp(&(*other as i32))
328 /// Trait for values that can be compared for a sort-order.
330 /// The comparison must satisfy, for all `a`, `b` and `c`:
332 /// - antisymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
333 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
335 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
336 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
341 /// This trait can be used with `#[derive]`. When `derive`d, it will produce a lexicographic
342 /// ordering based on the top-to-bottom declaration order of the struct's members.
344 /// ## How can I implement `Ord`?
346 /// PartialOrd only requires implementation of the `partial_cmp` method, with the others generated
347 /// from default implementations.
349 /// However it remains possible to implement the others separately for types which do not have a
350 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
351 /// false` (cf. IEEE 754-2008 section 5.11).
353 /// `PartialOrd` requires your type to be `PartialEq`.
355 /// If your type is `Ord`, you can implement `partial_cmp()` by using `cmp()`:
358 /// use std::cmp::Ordering;
367 /// impl PartialOrd for Person {
368 /// fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
369 /// Some(self.cmp(other))
373 /// impl Ord for Person {
374 /// fn cmp(&self, other: &Person) -> Ordering {
375 /// self.height.cmp(&other.height)
379 /// impl PartialEq for Person {
380 /// fn eq(&self, other: &Person) -> bool {
381 /// self.height == other.height
386 /// You may also find it useful to use `partial_cmp()` on your type`s fields. Here
387 /// is an example of `Person` types who have a floating-point `height` field that
388 /// is the only field to be used for sorting:
391 /// use std::cmp::Ordering;
399 /// impl PartialOrd for Person {
400 /// fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
401 /// self.height.partial_cmp(&other.height)
405 /// impl PartialEq for Person {
406 /// fn eq(&self, other: &Person) -> bool {
407 /// self.height == other.height
418 /// assert_eq!(x < y, true);
419 /// assert_eq!(x.lt(&y), true);
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
424 /// This method returns an ordering between `self` and `other` values if one exists.
429 /// use std::cmp::Ordering;
431 /// let result = 1.0.partial_cmp(&2.0);
432 /// assert_eq!(result, Some(Ordering::Less));
434 /// let result = 1.0.partial_cmp(&1.0);
435 /// assert_eq!(result, Some(Ordering::Equal));
437 /// let result = 2.0.partial_cmp(&1.0);
438 /// assert_eq!(result, Some(Ordering::Greater));
441 /// When comparison is impossible:
444 /// let result = std::f64::NAN.partial_cmp(&1.0);
445 /// assert_eq!(result, None);
447 #[stable(feature = "rust1", since = "1.0.0")]
448 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
450 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
455 /// let result = 1.0 < 2.0;
456 /// assert_eq!(result, true);
458 /// let result = 2.0 < 1.0;
459 /// assert_eq!(result, false);
462 #[stable(feature = "rust1", since = "1.0.0")]
463 fn lt(&self, other: &Rhs) -> bool {
464 match self.partial_cmp(other) {
470 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
476 /// let result = 1.0 <= 2.0;
477 /// assert_eq!(result, true);
479 /// let result = 2.0 <= 2.0;
480 /// assert_eq!(result, true);
483 #[stable(feature = "rust1", since = "1.0.0")]
484 fn le(&self, other: &Rhs) -> bool {
485 match self.partial_cmp(other) {
486 Some(Less) | Some(Equal) => true,
491 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
496 /// let result = 1.0 > 2.0;
497 /// assert_eq!(result, false);
499 /// let result = 2.0 > 2.0;
500 /// assert_eq!(result, false);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 fn gt(&self, other: &Rhs) -> bool {
505 match self.partial_cmp(other) {
506 Some(Greater) => true,
511 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
517 /// let result = 2.0 >= 1.0;
518 /// assert_eq!(result, true);
520 /// let result = 2.0 >= 2.0;
521 /// assert_eq!(result, true);
524 #[stable(feature = "rust1", since = "1.0.0")]
525 fn ge(&self, other: &Rhs) -> bool {
526 match self.partial_cmp(other) {
527 Some(Greater) | Some(Equal) => true,
533 /// Compare and return the minimum of two values.
535 /// Returns the first argument if the comparison determines them to be equal.
542 /// assert_eq!(1, cmp::min(1, 2));
543 /// assert_eq!(2, cmp::min(2, 2));
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn min<T: Ord>(v1: T, v2: T) -> T {
548 if v1 <= v2 { v1 } else { v2 }
551 /// Compare and return the maximum of two values.
553 /// Returns the second argument if the comparison determines them to be equal.
560 /// assert_eq!(2, cmp::max(1, 2));
561 /// assert_eq!(2, cmp::max(2, 2));
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn max<T: Ord>(v1: T, v2: T) -> T {
566 if v2 >= v1 { v2 } else { v1 }
569 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
571 use cmp::Ordering::{self, Less, Greater, Equal};
573 macro_rules! partial_eq_impl {
575 #[stable(feature = "rust1", since = "1.0.0")]
576 impl PartialEq for $t {
578 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
580 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
585 #[stable(feature = "rust1", since = "1.0.0")]
586 impl PartialEq for () {
588 fn eq(&self, _other: &()) -> bool { true }
590 fn ne(&self, _other: &()) -> bool { false }
594 bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64
597 macro_rules! eq_impl {
599 #[stable(feature = "rust1", since = "1.0.0")]
604 eq_impl! { () bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
606 macro_rules! partial_ord_impl {
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl PartialOrd for $t {
611 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
612 match (self <= other, self >= other) {
613 (false, false) => None,
614 (false, true) => Some(Greater),
615 (true, false) => Some(Less),
616 (true, true) => Some(Equal),
620 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
622 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
624 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
626 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl PartialOrd for () {
634 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl PartialOrd for bool {
642 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
643 (*self as u8).partial_cmp(&(*other as u8))
647 partial_ord_impl! { f32 f64 }
649 macro_rules! ord_impl {
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl PartialOrd for $t {
654 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
655 Some(self.cmp(other))
658 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
660 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
662 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
664 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
667 #[stable(feature = "rust1", since = "1.0.0")]
670 fn cmp(&self, other: &$t) -> Ordering {
671 if *self == *other { Equal }
672 else if *self < *other { Less }
679 #[stable(feature = "rust1", since = "1.0.0")]
682 fn cmp(&self, _other: &()) -> Ordering { Equal }
685 #[stable(feature = "rust1", since = "1.0.0")]
688 fn cmp(&self, other: &bool) -> Ordering {
689 (*self as u8).cmp(&(*other as u8))
693 ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
695 #[unstable(feature = "never_type", issue = "35121")]
696 impl PartialEq for ! {
697 fn eq(&self, _: &!) -> bool {
702 #[unstable(feature = "never_type", issue = "35121")]
705 #[unstable(feature = "never_type", issue = "35121")]
706 impl PartialOrd for ! {
707 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
712 #[unstable(feature = "never_type", issue = "35121")]
714 fn cmp(&self, _: &!) -> Ordering {
721 #[stable(feature = "rust1", since = "1.0.0")]
722 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a A where A: PartialEq<B> {
724 fn eq(&self, other: & &'b B) -> bool { PartialEq::eq(*self, *other) }
726 fn ne(&self, other: & &'b B) -> bool { PartialEq::ne(*self, *other) }
728 #[stable(feature = "rust1", since = "1.0.0")]
729 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b B> for &'a A where A: PartialOrd<B> {
731 fn partial_cmp(&self, other: &&'b B) -> Option<Ordering> {
732 PartialOrd::partial_cmp(*self, *other)
735 fn lt(&self, other: & &'b B) -> bool { PartialOrd::lt(*self, *other) }
737 fn le(&self, other: & &'b B) -> bool { PartialOrd::le(*self, *other) }
739 fn ge(&self, other: & &'b B) -> bool { PartialOrd::ge(*self, *other) }
741 fn gt(&self, other: & &'b B) -> bool { PartialOrd::gt(*self, *other) }
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl<'a, A: ?Sized> Ord for &'a A where A: Ord {
746 fn cmp(&self, other: & &'a A) -> Ordering { Ord::cmp(*self, *other) }
748 #[stable(feature = "rust1", since = "1.0.0")]
749 impl<'a, A: ?Sized> Eq for &'a A where A: Eq {}
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a mut A where A: PartialEq<B> {
756 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
758 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
760 #[stable(feature = "rust1", since = "1.0.0")]
761 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b mut B> for &'a mut A where A: PartialOrd<B> {
763 fn partial_cmp(&self, other: &&'b mut B) -> Option<Ordering> {
764 PartialOrd::partial_cmp(*self, *other)
767 fn lt(&self, other: &&'b mut B) -> bool { PartialOrd::lt(*self, *other) }
769 fn le(&self, other: &&'b mut B) -> bool { PartialOrd::le(*self, *other) }
771 fn ge(&self, other: &&'b mut B) -> bool { PartialOrd::ge(*self, *other) }
773 fn gt(&self, other: &&'b mut B) -> bool { PartialOrd::gt(*self, *other) }
775 #[stable(feature = "rust1", since = "1.0.0")]
776 impl<'a, A: ?Sized> Ord for &'a mut A where A: Ord {
778 fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
780 #[stable(feature = "rust1", since = "1.0.0")]
781 impl<'a, A: ?Sized> Eq for &'a mut A where A: Eq {}
783 #[stable(feature = "rust1", since = "1.0.0")]
784 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a A where A: PartialEq<B> {
786 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
788 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a mut A where A: PartialEq<B> {
794 fn eq(&self, other: &&'b B) -> bool { PartialEq::eq(*self, *other) }
796 fn ne(&self, other: &&'b B) -> bool { PartialEq::ne(*self, *other) }