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.
18 #![stable(feature = "rust1", since = "1.0.0")]
20 use self::Ordering::*;
24 use option::Option::{self, Some};
26 /// Trait for equality comparisons which are [partial equivalence
27 /// relations](http://en.wikipedia.org/wiki/Partial_equivalence_relation).
29 /// This trait allows for partial equality, for types that do not have a full
30 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
31 /// so floating point types implement `PartialEq` but not `Eq`.
33 /// Formally, the equality must be (for all `a`, `b` and `c`):
35 /// - symmetric: `a == b` implies `b == a`; and
36 /// - transitive: `a == b` and `b == c` implies `a == c`.
38 /// Note that these requirements mean that the trait itself must be implemented
39 /// symmetrically and transitively: if `T: PartialEq<U>` and `U: PartialEq<V>`
40 /// then `U: PartialEq<T>` and `T: PartialEq<V>`.
42 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined
43 /// in terms of it by default. Any manual implementation of `ne` *must* respect
44 /// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub trait PartialEq<Rhs: ?Sized = Self> {
49 /// This method tests for `self` and `other` values to be equal, and is used
51 #[stable(feature = "rust1", since = "1.0.0")]
52 fn eq(&self, other: &Rhs) -> bool;
54 /// This method tests for `!=`.
56 #[stable(feature = "rust1", since = "1.0.0")]
57 fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
60 /// Trait for equality comparisons which are [equivalence relations](
61 /// https://en.wikipedia.org/wiki/Equivalence_relation).
63 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
64 /// be (for all `a`, `b` and `c`):
66 /// - reflexive: `a == a`;
67 /// - symmetric: `a == b` implies `b == a`; and
68 /// - transitive: `a == b` and `b == c` implies `a == c`.
70 /// This property cannot be checked by the compiler, and therefore `Eq` implies
71 /// `PartialEq`, and has no extra methods.
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub trait Eq: PartialEq<Self> {
74 // FIXME #13101: this method is used solely by #[deriving] to
75 // assert that every component of a type implements #[deriving]
76 // itself, the current deriving infrastructure means doing this
77 // assertion without using a method on this trait is nearly
80 // This should never be implemented by hand.
83 #[stable(feature = "rust1", since = "1.0.0")]
84 fn assert_receiver_is_total_eq(&self) {}
87 /// An `Ordering` is the result of a comparison between two values.
92 /// use std::cmp::Ordering;
94 /// let result = 1.cmp(&2);
95 /// assert_eq!(Ordering::Less, result);
97 /// let result = 1.cmp(&1);
98 /// assert_eq!(Ordering::Equal, result);
100 /// let result = 2.cmp(&1);
101 /// assert_eq!(Ordering::Greater, result);
103 #[derive(Clone, Copy, PartialEq, Debug)]
104 #[stable(feature = "rust1", since = "1.0.0")]
106 /// An ordering where a compared value is less [than another].
107 #[stable(feature = "rust1", since = "1.0.0")]
109 /// An ordering where a compared value is equal [to another].
110 #[stable(feature = "rust1", since = "1.0.0")]
112 /// An ordering where a compared value is greater [than another].
113 #[stable(feature = "rust1", since = "1.0.0")]
118 unsafe fn from_i8_unchecked(v: i8) -> Ordering {
122 /// Reverse the `Ordering`.
124 /// * `Less` becomes `Greater`.
125 /// * `Greater` becomes `Less`.
126 /// * `Equal` becomes `Equal`.
133 /// use std::cmp::Ordering;
135 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
136 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
137 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
140 /// This method can be used to reverse a comparison:
143 /// use std::cmp::Ordering;
145 /// let mut data: &mut [_] = &mut [2, 10, 5, 8];
147 /// // sort the array from largest to smallest.
148 /// data.sort_by(|a, b| a.cmp(b).reverse());
150 /// let b: &mut [_] = &mut [10, 8, 5, 2];
151 /// assert!(data == b);
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub fn reverse(self) -> Ordering {
157 // this compiles really nicely (to a single instruction);
158 // an explicit match has a pile of branches and
161 // NB. it is safe because of the explicit discriminants
163 Ordering::from_i8_unchecked(-(self as i8))
168 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
170 /// An order is a total order if it is (for all `a`, `b` and `c`):
172 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
173 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
175 /// When this trait is `derive`d, it produces a lexicographic ordering.
176 #[stable(feature = "rust1", since = "1.0.0")]
177 pub trait Ord: Eq + PartialOrd<Self> {
178 /// This method returns an `Ordering` between `self` and `other`.
180 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
181 /// `self <operator> other` if true.
186 /// use std::cmp::Ordering;
188 /// assert_eq!(5.cmp(&10), Ordering::Less);
189 /// assert_eq!(10.cmp(&5), Ordering::Greater);
190 /// assert_eq!(5.cmp(&5), Ordering::Equal);
192 #[stable(feature = "rust1", since = "1.0.0")]
193 fn cmp(&self, other: &Self) -> Ordering;
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl Eq for Ordering {}
199 #[stable(feature = "rust1", since = "1.0.0")]
200 impl Ord for Ordering {
202 #[stable(feature = "rust1", since = "1.0.0")]
203 fn cmp(&self, other: &Ordering) -> Ordering {
204 (*self as i32).cmp(&(*other as i32))
208 #[stable(feature = "rust1", since = "1.0.0")]
209 impl PartialOrd for Ordering {
211 #[stable(feature = "rust1", since = "1.0.0")]
212 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
213 (*self as i32).partial_cmp(&(*other as i32))
217 /// Trait for values that can be compared for a sort-order.
219 /// The comparison must satisfy, for all `a`, `b` and `c`:
221 /// - antisymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
222 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
224 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
225 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
228 /// PartialOrd only requires implementation of the `partial_cmp` method, with the others generated
229 /// from default implementations.
231 /// However it remains possible to implement the others separately for types which do not have a
232 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
233 /// false` (cf. IEEE 754-2008 section 5.11).
235 #[stable(feature = "rust1", since = "1.0.0")]
236 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
237 /// This method returns an ordering between `self` and `other` values if one exists.
242 /// use std::cmp::Ordering;
244 /// let result = 1.0.partial_cmp(&2.0);
245 /// assert_eq!(result, Some(Ordering::Less));
247 /// let result = 1.0.partial_cmp(&1.0);
248 /// assert_eq!(result, Some(Ordering::Equal));
250 /// let result = 2.0.partial_cmp(&1.0);
251 /// assert_eq!(result, Some(Ordering::Greater));
254 /// When comparison is impossible:
257 /// let result = std::f64::NAN.partial_cmp(&1.0);
258 /// assert_eq!(result, None);
260 #[stable(feature = "rust1", since = "1.0.0")]
261 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
263 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
268 /// use std::cmp::Ordering;
270 /// let result = 1.0 < 2.0;
271 /// assert_eq!(result, true);
273 /// let result = 2.0 < 1.0;
274 /// assert_eq!(result, false);
277 #[stable(feature = "rust1", since = "1.0.0")]
278 fn lt(&self, other: &Rhs) -> bool {
279 match self.partial_cmp(other) {
285 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
291 /// let result = 1.0 <= 2.0;
292 /// assert_eq!(result, true);
294 /// let result = 2.0 <= 2.0;
295 /// assert_eq!(result, true);
298 #[stable(feature = "rust1", since = "1.0.0")]
299 fn le(&self, other: &Rhs) -> bool {
300 match self.partial_cmp(other) {
301 Some(Less) | Some(Equal) => true,
306 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
311 /// let result = 1.0 > 2.0;
312 /// assert_eq!(result, false);
314 /// let result = 2.0 > 2.0;
315 /// assert_eq!(result, false);
318 #[stable(feature = "rust1", since = "1.0.0")]
319 fn gt(&self, other: &Rhs) -> bool {
320 match self.partial_cmp(other) {
321 Some(Greater) => true,
326 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
332 /// let result = 2.0 >= 1.0;
333 /// assert_eq!(result, true);
335 /// let result = 2.0 >= 2.0;
336 /// assert_eq!(result, true);
339 #[stable(feature = "rust1", since = "1.0.0")]
340 fn ge(&self, other: &Rhs) -> bool {
341 match self.partial_cmp(other) {
342 Some(Greater) | Some(Equal) => true,
348 /// Compare and return the minimum of two values.
350 /// Returns the first argument if the comparison determines them to be equal.
357 /// assert_eq!(1, cmp::min(1, 2));
358 /// assert_eq!(2, cmp::min(2, 2));
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn min<T: Ord>(v1: T, v2: T) -> T {
363 if v1 <= v2 { v1 } else { v2 }
366 /// Compare and return the maximum of two values.
368 /// Returns the second argument if the comparison determines them to be equal.
375 /// assert_eq!(2, cmp::max(1, 2));
376 /// assert_eq!(2, cmp::max(2, 2));
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn max<T: Ord>(v1: T, v2: T) -> T {
381 if v2 >= v1 { v2 } else { v1 }
384 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
386 use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering};
387 use cmp::Ordering::{Less, Greater, Equal};
390 use option::Option::{Some, None};
392 macro_rules! partial_eq_impl {
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl PartialEq for $t {
397 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
399 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
404 #[stable(feature = "rust1", since = "1.0.0")]
405 impl PartialEq for () {
407 fn eq(&self, _other: &()) -> bool { true }
409 fn ne(&self, _other: &()) -> bool { false }
413 bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64
416 macro_rules! eq_impl {
418 #[stable(feature = "rust1", since = "1.0.0")]
423 eq_impl! { () bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
425 macro_rules! partial_ord_impl {
427 #[stable(feature = "rust1", since = "1.0.0")]
428 impl PartialOrd for $t {
430 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
431 match (self <= other, self >= other) {
432 (false, false) => None,
433 (false, true) => Some(Greater),
434 (true, false) => Some(Less),
435 (true, true) => Some(Equal),
439 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
441 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
443 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
445 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl PartialOrd for () {
453 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl PartialOrd for bool {
461 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
462 (*self as u8).partial_cmp(&(*other as u8))
466 partial_ord_impl! { f32 f64 }
468 macro_rules! ord_impl {
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl PartialOrd for $t {
473 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
474 Some(self.cmp(other))
477 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
479 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
481 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
483 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
486 #[stable(feature = "rust1", since = "1.0.0")]
489 fn cmp(&self, other: &$t) -> Ordering {
490 if *self == *other { Equal }
491 else if *self < *other { Less }
498 #[stable(feature = "rust1", since = "1.0.0")]
501 fn cmp(&self, _other: &()) -> Ordering { Equal }
504 #[stable(feature = "rust1", since = "1.0.0")]
507 fn cmp(&self, other: &bool) -> Ordering {
508 (*self as u8).cmp(&(*other as u8))
512 ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a A where A: PartialEq<B> {
519 fn eq(&self, other: & &'b B) -> bool { PartialEq::eq(*self, *other) }
521 fn ne(&self, other: & &'b B) -> bool { PartialEq::ne(*self, *other) }
523 #[stable(feature = "rust1", since = "1.0.0")]
524 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b B> for &'a A where A: PartialOrd<B> {
526 fn partial_cmp(&self, other: &&'b B) -> Option<Ordering> {
527 PartialOrd::partial_cmp(*self, *other)
530 fn lt(&self, other: & &'b B) -> bool { PartialOrd::lt(*self, *other) }
532 fn le(&self, other: & &'b B) -> bool { PartialOrd::le(*self, *other) }
534 fn ge(&self, other: & &'b B) -> bool { PartialOrd::ge(*self, *other) }
536 fn gt(&self, other: & &'b B) -> bool { PartialOrd::gt(*self, *other) }
538 #[stable(feature = "rust1", since = "1.0.0")]
539 impl<'a, A: ?Sized> Ord for &'a A where A: Ord {
541 fn cmp(&self, other: & &'a A) -> Ordering { Ord::cmp(*self, *other) }
543 #[stable(feature = "rust1", since = "1.0.0")]
544 impl<'a, A: ?Sized> Eq for &'a A where A: Eq {}
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a mut A where A: PartialEq<B> {
551 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
553 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
555 #[stable(feature = "rust1", since = "1.0.0")]
556 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b mut B> for &'a mut A where A: PartialOrd<B> {
558 fn partial_cmp(&self, other: &&'b mut B) -> Option<Ordering> {
559 PartialOrd::partial_cmp(*self, *other)
562 fn lt(&self, other: &&'b mut B) -> bool { PartialOrd::lt(*self, *other) }
564 fn le(&self, other: &&'b mut B) -> bool { PartialOrd::le(*self, *other) }
566 fn ge(&self, other: &&'b mut B) -> bool { PartialOrd::ge(*self, *other) }
568 fn gt(&self, other: &&'b mut B) -> bool { PartialOrd::gt(*self, *other) }
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl<'a, A: ?Sized> Ord for &'a mut A where A: Ord {
573 fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
575 #[stable(feature = "rust1", since = "1.0.0")]
576 impl<'a, A: ?Sized> Eq for &'a mut A where A: Eq {}
578 #[stable(feature = "rust1", since = "1.0.0")]
579 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a A where A: PartialEq<B> {
581 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
583 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
586 #[stable(feature = "rust1", since = "1.0.0")]
587 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a mut A where A: PartialEq<B> {
589 fn eq(&self, other: &&'b B) -> bool { PartialEq::eq(*self, *other) }
591 fn ne(&self, other: &&'b B) -> bool { PartialEq::ne(*self, *other) }