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 //! Defines the `PartialOrd` and `PartialEq` comparison traits.
13 //! This module defines both `PartialOrd` and `PartialEq` traits which are used by the
14 //! compiler to implement comparison operators. Rust programs may implement
15 //!`PartialOrd` to overload the `<`, `<=`, `>`, and `>=` operators, and may implement
16 //! `PartialEq` to overload the `==` and `!=` operators.
18 //! For example, to define a type with a customized definition for the PartialEq
19 //! operators, you could do the following:
22 //! use core::num::SignedInt;
25 //! struct SketchyNum {
29 //! // Our implementation of `PartialEq` to support `==` and `!=`.
30 //! impl PartialEq for SketchyNum {
31 //! // Our custom eq allows numbers which are near each other to be equal! :D
32 //! fn eq(&self, other: &SketchyNum) -> bool {
33 //! (self.num - other.num).abs() < 5
37 //! // Now these binary operators will work when applied!
38 //! assert!(SketchyNum {num: 37} == SketchyNum {num: 34});
39 //! assert!(SketchyNum {num: 25} != SketchyNum {num: 57});
44 use self::Ordering::*;
47 use option::Option::{self, Some, None};
49 /// Trait for equality comparisons which are [partial equivalence relations](
50 /// http://en.wikipedia.org/wiki/Partial_equivalence_relation).
52 /// This trait allows for partial equality, for types that do not have a full
53 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
54 /// so floating point types implement `PartialEq` but not `Eq`.
56 /// Formally, the equality must be (for all `a`, `b` and `c`):
58 /// - symmetric: `a == b` implies `b == a`; and
59 /// - transitive: `a == b` and `b == c` implies `a == c`.
61 /// Note that these requirements mean that the trait itself must be
62 /// implemented symmetrically and transitively: if `T: PartialEq<U>`
63 /// and `U: PartialEq<V>` then `U: PartialEq<T>` and `T:
66 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined
67 /// in terms of it by default. Any manual implementation of `ne` *must* respect
68 /// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
72 pub trait PartialEq<Sized? Rhs = Self> for Sized? {
73 /// This method tests for `self` and `other` values to be equal, and is used by `==`.
75 fn eq(&self, other: &Rhs) -> bool;
77 /// This method tests for `!=`.
80 fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
83 /// Trait for equality comparisons which are [equivalence relations](
84 /// https://en.wikipedia.org/wiki/Equivalence_relation).
86 /// This means, that in addition to `a == b` and `a != b` being strict
87 /// inverses, the equality must be (for all `a`, `b` and `c`):
89 /// - reflexive: `a == a`;
90 /// - symmetric: `a == b` implies `b == a`; and
91 /// - transitive: `a == b` and `b == c` implies `a == c`.
93 pub trait Eq for Sized?: PartialEq<Self> {
94 // FIXME #13101: this method is used solely by #[deriving] to
95 // assert that every component of a type implements #[deriving]
96 // itself, the current deriving infrastructure means doing this
97 // assertion without using a method on this trait is nearly
100 // This should never be implemented by hand.
103 fn assert_receiver_is_total_eq(&self) {}
106 /// An ordering is, e.g, a result of a comparison between two values.
107 #[derive(Clone, Copy, PartialEq, Show)]
110 /// An ordering where a compared value is less [than another].
113 /// An ordering where a compared value is equal [to another].
116 /// An ordering where a compared value is greater [than another].
122 /// Reverse the `Ordering`, so that `Less` becomes `Greater` and
128 /// use std::cmp::Ordering::{Less, Equal, Greater};
130 /// assert_eq!(Less.reverse(), Greater);
131 /// assert_eq!(Equal.reverse(), Equal);
132 /// assert_eq!(Greater.reverse(), Less);
134 /// let mut data: &mut [_] = &mut [2u, 10, 5, 8];
136 /// // sort the array from largest to smallest.
137 /// data.sort_by(|a, b| a.cmp(b).reverse());
139 /// let b: &mut [_] = &mut [10u, 8, 5, 2];
140 /// assert!(data == b);
144 pub fn reverse(self) -> Ordering {
146 // this compiles really nicely (to a single instruction);
147 // an explicit match has a pile of branches and
150 // NB. it is safe because of the explicit discriminants
152 ::mem::transmute::<_, Ordering>(-(self as i8))
157 /// Trait for types that form a [total order](
158 /// https://en.wikipedia.org/wiki/Total_order).
160 /// An order is a total order if it is (for all `a`, `b` and `c`):
162 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is
164 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for
165 /// both `==` and `>`.
167 pub trait Ord for Sized?: Eq + PartialOrd<Self> {
168 /// This method returns an ordering between `self` and `other` values.
170 /// By convention, `self.cmp(&other)` returns the ordering matching
171 /// the expression `self <operator> other` if true. For example:
174 /// use std::cmp::Ordering::{Less, Equal, Greater};
176 /// assert_eq!( 5u.cmp(&10), Less); // because 5 < 10
177 /// assert_eq!(10u.cmp(&5), Greater); // because 10 > 5
178 /// assert_eq!( 5u.cmp(&5), Equal); // because 5 == 5
181 fn cmp(&self, other: &Self) -> Ordering;
185 impl Eq for Ordering {}
188 impl Ord for Ordering {
191 fn cmp(&self, other: &Ordering) -> Ordering {
192 (*self as int).cmp(&(*other as int))
197 impl PartialOrd for Ordering {
200 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
201 (*self as int).partial_cmp(&(*other as int))
205 /// Trait for values that can be compared for a sort-order.
207 /// The comparison must satisfy, for all `a`, `b` and `c`:
209 /// - antisymmetry: if `a < b` then `!(a > b)` and vice versa; and
210 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for
211 /// both `==` and `>`.
213 /// Note that these requirements mean that the trait itself must be
214 /// implemented symmetrically and transitively: if `T: PartialOrd<U>`
215 /// and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
218 /// PartialOrd only requires implementation of the `partial_cmp` method,
219 /// with the others generated from default implementations.
221 /// However it remains possible to implement the others separately for types
222 /// which do not have a total order. For example, for floating point numbers,
223 /// `NaN < 0 == false` and `NaN >= 0 == false` (cf. IEEE 754-2008 section
227 pub trait PartialOrd<Sized? Rhs = Self> for Sized?: PartialEq<Rhs> {
228 /// This method returns an ordering between `self` and `other` values
231 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
233 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
236 fn lt(&self, other: &Rhs) -> bool {
237 match self.partial_cmp(other) {
243 /// This method tests less than or equal to (`<=`).
246 fn le(&self, other: &Rhs) -> bool {
247 match self.partial_cmp(other) {
248 Some(Less) | Some(Equal) => true,
253 /// This method tests greater than (`>`).
256 fn gt(&self, other: &Rhs) -> bool {
257 match self.partial_cmp(other) {
258 Some(Greater) => true,
263 /// This method tests greater than or equal to (`>=`).
266 fn ge(&self, other: &Rhs) -> bool {
267 match self.partial_cmp(other) {
268 Some(Greater) | Some(Equal) => true,
274 /// Compare and return the minimum of two values.
277 pub fn min<T: Ord>(v1: T, v2: T) -> T {
278 if v1 < v2 { v1 } else { v2 }
281 /// Compare and return the maximum of two values.
284 pub fn max<T: Ord>(v1: T, v2: T) -> T {
285 if v1 > v2 { v1 } else { v2 }
288 /// Compare and return the minimum of two values if there is one.
290 /// Returns the first argument if the comparison determines them to be equal.
293 pub fn partial_min<T: PartialOrd>(v1: T, v2: T) -> Option<T> {
294 match v1.partial_cmp(&v2) {
295 Some(Less) | Some(Equal) => Some(v1),
296 Some(Greater) => Some(v2),
301 /// Compare and return the maximum of two values if there is one.
303 /// Returns the first argument if the comparison determines them to be equal.
306 pub fn partial_max<T: PartialOrd>(v1: T, v2: T) -> Option<T> {
307 match v1.partial_cmp(&v2) {
308 Some(Less) => Some(v2),
309 Some(Equal) | Some(Greater) => Some(v1),
314 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
316 use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering};
317 use cmp::Ordering::{Less, Greater, Equal};
320 use option::Option::{Some, None};
322 macro_rules! partial_eq_impl {
325 impl PartialEq for $t {
327 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
329 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
335 impl PartialEq for () {
337 fn eq(&self, _other: &()) -> bool { true }
339 fn ne(&self, _other: &()) -> bool { false }
343 bool char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64
346 macro_rules! eq_impl {
353 eq_impl! { () bool char uint u8 u16 u32 u64 int i8 i16 i32 i64 }
355 macro_rules! partial_ord_impl {
358 impl PartialOrd for $t {
360 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
361 match (self <= other, self >= other) {
362 (false, false) => None,
363 (false, true) => Some(Greater),
364 (true, false) => Some(Less),
365 (true, true) => Some(Equal),
369 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
371 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
373 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
375 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
381 impl PartialOrd for () {
383 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
389 impl PartialOrd for bool {
391 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
392 (*self as u8).partial_cmp(&(*other as u8))
396 partial_ord_impl! { char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
398 macro_rules! ord_impl {
403 fn cmp(&self, other: &$t) -> Ordering {
404 if *self < *other { Less }
405 else if *self > *other { Greater }
415 fn cmp(&self, _other: &()) -> Ordering { Equal }
421 fn cmp(&self, other: &bool) -> Ordering {
422 (*self as u8).cmp(&(*other as u8))
426 ord_impl! { char uint u8 u16 u32 u64 int i8 i16 i32 i64 }
431 impl<'a, 'b, Sized? A, Sized? B> PartialEq<&'b B> for &'a A where A: PartialEq<B> {
433 fn eq(&self, other: & &'b B) -> bool { PartialEq::eq(*self, *other) }
435 fn ne(&self, other: & &'b B) -> bool { PartialEq::ne(*self, *other) }
438 impl<'a, 'b, Sized? A, Sized? B> PartialOrd<&'b B> for &'a A where A: PartialOrd<B> {
440 fn partial_cmp(&self, other: &&'b B) -> Option<Ordering> {
441 PartialOrd::partial_cmp(*self, *other)
444 fn lt(&self, other: & &'b B) -> bool { PartialOrd::lt(*self, *other) }
446 fn le(&self, other: & &'b B) -> bool { PartialOrd::le(*self, *other) }
448 fn ge(&self, other: & &'b B) -> bool { PartialOrd::ge(*self, *other) }
450 fn gt(&self, other: & &'b B) -> bool { PartialOrd::gt(*self, *other) }
453 impl<'a, Sized? A> Ord for &'a A where A: Ord {
455 fn cmp(&self, other: & &'a A) -> Ordering { Ord::cmp(*self, *other) }
458 impl<'a, Sized? A> Eq for &'a A where A: Eq {}
463 impl<'a, 'b, Sized? A, Sized? B> PartialEq<&'b mut B> for &'a mut A where A: PartialEq<B> {
465 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
467 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
470 impl<'a, 'b, Sized? A, Sized? B> PartialOrd<&'b mut B> for &'a mut A where A: PartialOrd<B> {
472 fn partial_cmp(&self, other: &&'b mut B) -> Option<Ordering> {
473 PartialOrd::partial_cmp(*self, *other)
476 fn lt(&self, other: &&'b mut B) -> bool { PartialOrd::lt(*self, *other) }
478 fn le(&self, other: &&'b mut B) -> bool { PartialOrd::le(*self, *other) }
480 fn ge(&self, other: &&'b mut B) -> bool { PartialOrd::ge(*self, *other) }
482 fn gt(&self, other: &&'b mut B) -> bool { PartialOrd::gt(*self, *other) }
485 impl<'a, Sized? A> Ord for &'a mut A where A: Ord {
487 fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
490 impl<'a, Sized? A> Eq for &'a mut A where A: Eq {}
493 impl<'a, 'b, Sized? A, Sized? B> PartialEq<&'b mut B> for &'a A where A: PartialEq<B> {
495 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
497 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
501 impl<'a, 'b, Sized? A, Sized? B> PartialEq<&'b B> for &'a mut A where A: PartialEq<B> {
503 fn eq(&self, other: &&'b B) -> bool { PartialEq::eq(*self, *other) }
505 fn ne(&self, other: &&'b B) -> bool { PartialEq::ne(*self, *other) }