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 by the compiler to
14 //! implement comparison operators. Rust programs may implement `PartialOrd` to overload the `<`,
15 //! `<=`, `>`, and `>=` operators, and may implement `PartialEq` to overload the `==` and `!=`
18 #![stable(feature = "rust1", since = "1.0.0")]
20 use self::Ordering::*;
23 use option::Option::{self, Some, None};
25 /// Trait for equality comparisons which are [partial equivalence relations](
26 /// http://en.wikipedia.org/wiki/Partial_equivalence_relation).
28 /// This trait allows for partial equality, for types that do not have a full equivalence relation.
29 /// For example, in floating point numbers `NaN != NaN`, so floating point types implement
30 /// `PartialEq` but not `Eq`.
32 /// Formally, the equality must be (for all `a`, `b` and `c`):
34 /// - symmetric: `a == b` implies `b == a`; and
35 /// - transitive: `a == b` and `b == c` implies `a == c`.
37 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
38 /// transitively: if `T: PartialEq<U>` and `U: PartialEq<V>` then `U: PartialEq<T>` and `T:
41 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined in terms of it by
42 /// default. Any manual implementation of `ne` *must* respect the rule that `eq` is a strict
43 /// inverse of `ne`; that is, `!(a == b)` if and only if `a != b`.
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub trait PartialEq<Rhs: ?Sized = Self> {
47 /// This method tests for `self` and `other` values to be equal, and is used by `==`.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 fn eq(&self, other: &Rhs) -> bool;
51 /// This method tests for `!=`.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
57 /// Trait for equality comparisons which are [equivalence relations](
58 /// https://en.wikipedia.org/wiki/Equivalence_relation).
60 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
61 /// be (for all `a`, `b` and `c`):
63 /// - reflexive: `a == a`;
64 /// - symmetric: `a == b` implies `b == a`; and
65 /// - transitive: `a == b` and `b == c` implies `a == c`.
67 /// This property cannot be checked by the compiler, and therefore `Eq` implies
68 /// `PartialEq`, and has no extra methods.
69 #[stable(feature = "rust1", since = "1.0.0")]
70 pub trait Eq: PartialEq<Self> {
71 // FIXME #13101: this method is used solely by #[deriving] to
72 // assert that every component of a type implements #[deriving]
73 // itself, the current deriving infrastructure means doing this
74 // assertion without using a method on this trait is nearly
77 // This should never be implemented by hand.
80 #[stable(feature = "rust1", since = "1.0.0")]
81 fn assert_receiver_is_total_eq(&self) {}
84 /// An `Ordering` is the result of a comparison between two values.
89 /// use std::cmp::Ordering;
91 /// let result = 1.cmp(&2);
92 /// assert_eq!(Ordering::Less, result);
94 /// let result = 1.cmp(&1);
95 /// assert_eq!(Ordering::Equal, result);
97 /// let result = 2.cmp(&1);
98 /// assert_eq!(Ordering::Greater, result);
100 #[derive(Clone, Copy, PartialEq, Debug)]
101 #[stable(feature = "rust1", since = "1.0.0")]
103 /// An ordering where a compared value is less [than another].
104 #[stable(feature = "rust1", since = "1.0.0")]
106 /// An ordering where a compared value is equal [to another].
107 #[stable(feature = "rust1", since = "1.0.0")]
109 /// An ordering where a compared value is greater [than another].
110 #[stable(feature = "rust1", since = "1.0.0")]
115 /// Reverse the `Ordering`.
117 /// * `Less` becomes `Greater`.
118 /// * `Greater` becomes `Less`.
119 /// * `Equal` becomes `Equal`.
126 /// use std::cmp::Ordering;
128 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
129 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
130 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
133 /// This method can be used to reverse a comparison:
136 /// use std::cmp::Ordering;
138 /// let mut data: &mut [_] = &mut [2, 10, 5, 8];
140 /// // sort the array from largest to smallest.
141 /// data.sort_by(|a, b| a.cmp(b).reverse());
143 /// let b: &mut [_] = &mut [10, 8, 5, 2];
144 /// assert!(data == b);
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn reverse(self) -> Ordering {
150 // this compiles really nicely (to a single instruction);
151 // an explicit match has a pile of branches and
154 // NB. it is safe because of the explicit discriminants
156 ::mem::transmute::<_, Ordering>(-(self as i8))
161 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
163 /// An order is a total order if it is (for all `a`, `b` and `c`):
165 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
166 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub trait Ord: Eq + PartialOrd<Self> {
169 /// This method returns an `Ordering` between `self` and `other`.
171 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
172 /// `self <operator> other` if true.
177 /// use std::cmp::Ordering;
179 /// assert_eq!(5.cmp(&10), Ordering::Less);
180 /// assert_eq!(10.cmp(&5), Ordering::Greater);
181 /// assert_eq!(5.cmp(&5), Ordering::Equal);
183 #[stable(feature = "rust1", since = "1.0.0")]
184 fn cmp(&self, other: &Self) -> Ordering;
187 #[stable(feature = "rust1", since = "1.0.0")]
188 impl Eq for Ordering {}
190 #[stable(feature = "rust1", since = "1.0.0")]
191 impl Ord for Ordering {
193 #[stable(feature = "rust1", since = "1.0.0")]
194 fn cmp(&self, other: &Ordering) -> Ordering {
195 (*self as i32).cmp(&(*other as i32))
199 #[stable(feature = "rust1", since = "1.0.0")]
200 impl PartialOrd for Ordering {
202 #[stable(feature = "rust1", since = "1.0.0")]
203 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
204 (*self as i32).partial_cmp(&(*other as i32))
208 /// Trait for values that can be compared for a sort-order.
210 /// The comparison must satisfy, for all `a`, `b` and `c`:
212 /// - antisymmetry: if `a < b` then `!(a > b)` and vice versa; and
213 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
215 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
216 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
219 /// PartialOrd only requires implementation of the `partial_cmp` method, with the others generated
220 /// from default implementations.
222 /// However it remains possible to implement the others separately for types which do not have a
223 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
224 /// false` (cf. IEEE 754-2008 section 5.11).
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
228 /// This method returns an ordering between `self` and `other` values if one exists.
233 /// use std::cmp::Ordering;
235 /// let result = 1.0.partial_cmp(&2.0);
236 /// assert_eq!(result, Some(Ordering::Less));
238 /// let result = 1.0.partial_cmp(&1.0);
239 /// assert_eq!(result, Some(Ordering::Equal));
241 /// let result = 2.0.partial_cmp(&1.0);
242 /// assert_eq!(result, Some(Ordering::Greater));
245 /// When comparison is impossible:
248 /// let result = std::f64::NAN.partial_cmp(&1.0);
249 /// assert_eq!(result, None);
251 #[stable(feature = "rust1", since = "1.0.0")]
252 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
254 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
259 /// use std::cmp::Ordering;
261 /// let result = 1.0 < 2.0;
262 /// assert_eq!(result, true);
264 /// let result = 2.0 < 1.0;
265 /// assert_eq!(result, false);
268 #[stable(feature = "rust1", since = "1.0.0")]
269 fn lt(&self, other: &Rhs) -> bool {
270 match self.partial_cmp(other) {
276 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
282 /// let result = 1.0 <= 2.0;
283 /// assert_eq!(result, true);
285 /// let result = 2.0 <= 2.0;
286 /// assert_eq!(result, true);
289 #[stable(feature = "rust1", since = "1.0.0")]
290 fn le(&self, other: &Rhs) -> bool {
291 match self.partial_cmp(other) {
292 Some(Less) | Some(Equal) => true,
297 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
302 /// let result = 1.0 > 2.0;
303 /// assert_eq!(result, false);
305 /// let result = 2.0 > 2.0;
306 /// assert_eq!(result, false);
309 #[stable(feature = "rust1", since = "1.0.0")]
310 fn gt(&self, other: &Rhs) -> bool {
311 match self.partial_cmp(other) {
312 Some(Greater) => true,
317 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
323 /// let result = 2.0 >= 1.0;
324 /// assert_eq!(result, true);
326 /// let result = 2.0 >= 2.0;
327 /// assert_eq!(result, true);
330 #[stable(feature = "rust1", since = "1.0.0")]
331 fn ge(&self, other: &Rhs) -> bool {
332 match self.partial_cmp(other) {
333 Some(Greater) | Some(Equal) => true,
339 /// Compare and return the minimum of two values.
341 /// Returns the first argument if the comparison determines them to be equal.
348 /// assert_eq!(1, cmp::min(1, 2));
349 /// assert_eq!(2, cmp::min(2, 2));
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn min<T: Ord>(v1: T, v2: T) -> T {
354 if v1 <= v2 { v1 } else { v2 }
357 /// Compare and return the maximum of two values.
359 /// Returns the second argument if the comparison determines them to be equal.
366 /// assert_eq!(2, cmp::max(1, 2));
367 /// assert_eq!(2, cmp::max(2, 2));
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn max<T: Ord>(v1: T, v2: T) -> T {
372 if v2 >= v1 { v2 } else { v1 }
375 /// Compare and return the minimum of two values if there is one.
377 /// Returns the first argument if the comparison determines them to be equal.
382 /// # #![feature(core)]
385 /// assert_eq!(Some(1), cmp::partial_min(1, 2));
386 /// assert_eq!(Some(2), cmp::partial_min(2, 2));
389 /// When comparison is impossible:
392 /// # #![feature(core)]
395 /// let result = cmp::partial_min(std::f64::NAN, 1.0);
396 /// assert_eq!(result, None);
399 #[unstable(feature = "core")]
400 pub fn partial_min<T: PartialOrd>(v1: T, v2: T) -> Option<T> {
401 match v1.partial_cmp(&v2) {
402 Some(Less) | Some(Equal) => Some(v1),
403 Some(Greater) => Some(v2),
408 /// Compare and return the maximum of two values if there is one.
410 /// Returns the second argument if the comparison determines them to be equal.
415 /// # #![feature(core)]
418 /// assert_eq!(Some(2), cmp::partial_max(1, 2));
419 /// assert_eq!(Some(2), cmp::partial_max(2, 2));
422 /// When comparison is impossible:
425 /// # #![feature(core)]
428 /// let result = cmp::partial_max(std::f64::NAN, 1.0);
429 /// assert_eq!(result, None);
432 #[unstable(feature = "core")]
433 pub fn partial_max<T: PartialOrd>(v1: T, v2: T) -> Option<T> {
434 match v1.partial_cmp(&v2) {
435 Some(Equal) | Some(Less) => Some(v2),
436 Some(Greater) => Some(v1),
441 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
443 use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering};
444 use cmp::Ordering::{Less, Greater, Equal};
447 use option::Option::{Some, None};
449 macro_rules! partial_eq_impl {
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl PartialEq for $t {
454 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
456 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl PartialEq for () {
464 fn eq(&self, _other: &()) -> bool { true }
466 fn ne(&self, _other: &()) -> bool { false }
470 bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64
473 macro_rules! eq_impl {
475 #[stable(feature = "rust1", since = "1.0.0")]
480 eq_impl! { () bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
482 macro_rules! partial_ord_impl {
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl PartialOrd for $t {
487 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
488 match (self <= other, self >= other) {
489 (false, false) => None,
490 (false, true) => Some(Greater),
491 (true, false) => Some(Less),
492 (true, true) => Some(Equal),
496 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
498 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
500 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
502 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl PartialOrd for () {
510 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl PartialOrd for bool {
518 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
519 (*self as u8).partial_cmp(&(*other as u8))
523 partial_ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
525 macro_rules! ord_impl {
527 #[stable(feature = "rust1", since = "1.0.0")]
530 fn cmp(&self, other: &$t) -> Ordering {
531 if *self < *other { Less }
532 else if *self > *other { Greater }
539 #[stable(feature = "rust1", since = "1.0.0")]
542 fn cmp(&self, _other: &()) -> Ordering { Equal }
545 #[stable(feature = "rust1", since = "1.0.0")]
548 fn cmp(&self, other: &bool) -> Ordering {
549 (*self as u8).cmp(&(*other as u8))
553 ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
557 #[stable(feature = "rust1", since = "1.0.0")]
558 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a A where A: PartialEq<B> {
560 fn eq(&self, other: & &'b B) -> bool { PartialEq::eq(*self, *other) }
562 fn ne(&self, other: & &'b B) -> bool { PartialEq::ne(*self, *other) }
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b B> for &'a A where A: PartialOrd<B> {
567 fn partial_cmp(&self, other: &&'b B) -> Option<Ordering> {
568 PartialOrd::partial_cmp(*self, *other)
571 fn lt(&self, other: & &'b B) -> bool { PartialOrd::lt(*self, *other) }
573 fn le(&self, other: & &'b B) -> bool { PartialOrd::le(*self, *other) }
575 fn ge(&self, other: & &'b B) -> bool { PartialOrd::ge(*self, *other) }
577 fn gt(&self, other: & &'b B) -> bool { PartialOrd::gt(*self, *other) }
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl<'a, A: ?Sized> Ord for &'a A where A: Ord {
582 fn cmp(&self, other: & &'a A) -> Ordering { Ord::cmp(*self, *other) }
584 #[stable(feature = "rust1", since = "1.0.0")]
585 impl<'a, A: ?Sized> Eq for &'a A where A: Eq {}
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a mut A where A: PartialEq<B> {
592 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
594 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
596 #[stable(feature = "rust1", since = "1.0.0")]
597 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b mut B> for &'a mut A where A: PartialOrd<B> {
599 fn partial_cmp(&self, other: &&'b mut B) -> Option<Ordering> {
600 PartialOrd::partial_cmp(*self, *other)
603 fn lt(&self, other: &&'b mut B) -> bool { PartialOrd::lt(*self, *other) }
605 fn le(&self, other: &&'b mut B) -> bool { PartialOrd::le(*self, *other) }
607 fn ge(&self, other: &&'b mut B) -> bool { PartialOrd::ge(*self, *other) }
609 fn gt(&self, other: &&'b mut B) -> bool { PartialOrd::gt(*self, *other) }
611 #[stable(feature = "rust1", since = "1.0.0")]
612 impl<'a, A: ?Sized> Ord for &'a mut A where A: Ord {
614 fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl<'a, A: ?Sized> Eq for &'a mut A where A: Eq {}
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a A where A: PartialEq<B> {
622 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
624 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
627 #[stable(feature = "rust1", since = "1.0.0")]
628 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a mut A where A: PartialEq<B> {
630 fn eq(&self, other: &&'b B) -> bool { PartialEq::eq(*self, *other) }
632 fn ne(&self, other: &&'b B) -> bool { PartialEq::ne(*self, *other) }