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:
23 //! struct SketchyNum {
27 //! // Our implementation of `PartialEq` to support `==` and `!=`.
28 //! impl PartialEq for SketchyNum {
29 //! // Our custom eq allows numbers which are near each other to be equal! :D
30 //! fn eq(&self, other: &SketchyNum) -> bool {
31 //! (self.num - other.num).abs() < 5
35 //! // Now these binary operators will work when applied!
36 //! assert!(SketchyNum {num: 37} == SketchyNum {num: 34});
37 //! assert!(SketchyNum {num: 25} != SketchyNum {num: 57});
40 use option::{Option, Some};
42 /// Trait for values that can be compared for equality and inequality.
44 /// This trait allows for partial equality, for types that do not have an
45 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
46 /// so floating point types implement `PartialEq` but not `Eq`.
48 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined
49 /// in terms of it by default. Any manual implementation of `ne` *must* respect
50 /// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
53 /// Eventually, this will be implemented by default for types that implement
57 /// This method tests for `self` and `other` values to be equal, and is used by `==`.
58 fn eq(&self, other: &Self) -> bool;
60 /// This method tests for `!=`.
62 fn ne(&self, other: &Self) -> bool { !self.eq(other) }
65 /// Trait for equality comparisons which are [equivalence relations](
66 /// https://en.wikipedia.org/wiki/Equivalence_relation).
68 /// This means, that in addition to `a == b` and `a != b` being strict
69 /// inverses, the equality must be (for all `a`, `b` and `c`):
71 /// - reflexive: `a == a`;
72 /// - symmetric: `a == b` implies `b == a`; and
73 /// - transitive: `a == b` and `b == c` implies `a == c`.
74 pub trait Eq: PartialEq {
75 // FIXME #13101: this method is used solely by #[deriving] to
76 // assert that every component of a type implements #[deriving]
77 // itself, the current deriving infrastructure means doing this
78 // assertion without using a method on this trait is nearly
81 // This should never be implemented by hand.
84 fn assert_receiver_is_total_eq(&self) {}
87 /// An ordering is, e.g, a result of a comparison between two values.
88 #[deriving(Clone, PartialEq, Show)]
90 /// An ordering where a compared value is less [than another].
92 /// An ordering where a compared value is equal [to another].
94 /// An ordering where a compared value is greater [than another].
98 /// Trait for types that form a [total order](
99 /// https://en.wikipedia.org/wiki/Total_order).
101 /// An order is a total order if it is (for all `a`, `b` and `c`):
103 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is
105 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for
106 /// both `==` and `>`.
107 pub trait Ord: Eq + PartialOrd {
108 /// This method returns an ordering between `self` and `other` values.
110 /// By convention, `self.cmp(&other)` returns the ordering matching
111 /// the expression `self <operator> other` if true. For example:
114 /// assert_eq!( 5u.cmp(&10), Less); // because 5 < 10
115 /// assert_eq!(10u.cmp(&5), Greater); // because 10 > 5
116 /// assert_eq!( 5u.cmp(&5), Equal); // because 5 == 5
118 fn cmp(&self, other: &Self) -> Ordering;
121 impl Eq for Ordering {}
123 impl Ord for Ordering {
125 fn cmp(&self, other: &Ordering) -> Ordering {
126 (*self as int).cmp(&(*other as int))
130 impl PartialOrd for Ordering {
132 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
133 (*self as int).partial_cmp(&(*other as int))
137 /// Combine orderings, lexically.
139 /// For example for a type `(int, int)`, two comparisons could be done.
140 /// If the first ordering is different, the first ordering is all that must be returned.
141 /// If the first ordering is equal, then second ordering is returned.
143 pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
150 /// Trait for values that can be compared for a sort-order.
152 /// PartialOrd only requires implementation of the `partial_cmp` method,
153 /// with the others generated from default implementations.
155 /// However it remains possible to implement the others separately for types
156 /// which do not have a total order. For example, for floating point numbers,
157 /// `NaN < 0 == false` and `NaN >= 0 == false` (cf. IEEE 754-2008 section
160 pub trait PartialOrd: PartialEq {
161 /// This method returns an ordering between `self` and `other` values
163 fn partial_cmp(&self, other: &Self) -> Option<Ordering>;
165 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
166 fn lt(&self, other: &Self) -> bool {
167 match self.partial_cmp(other) {
173 /// This method tests less than or equal to (`<=`).
175 fn le(&self, other: &Self) -> bool {
176 match self.partial_cmp(other) {
177 Some(Less) | Some(Equal) => true,
182 /// This method tests greater than (`>`).
184 fn gt(&self, other: &Self) -> bool {
185 match self.partial_cmp(other) {
186 Some(Greater) => true,
191 /// This method tests greater than or equal to (`>=`).
193 fn ge(&self, other: &Self) -> bool {
194 match self.partial_cmp(other) {
195 Some(Greater) | Some(Equal) => true,
201 /// The equivalence relation. Two values may be equivalent even if they are
202 /// of different types. The most common use case for this relation is
203 /// container types; e.g. it is often desirable to be able to use `&str`
204 /// values to look up entries in a container with `String` keys.
206 /// Implement this function to decide equivalent values.
207 fn equiv(&self, other: &T) -> bool;
210 /// Compare and return the minimum of two values.
212 pub fn min<T: Ord>(v1: T, v2: T) -> T {
213 if v1 < v2 { v1 } else { v2 }
216 /// Compare and return the maximum of two values.
218 pub fn max<T: Ord>(v1: T, v2: T) -> T {
219 if v1 > v2 { v1 } else { v2 }
222 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
224 use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering,
225 Less, Greater, Equal};
226 use option::{Option, Some, None};
228 macro_rules! eq_impl(
230 impl PartialEq for $t {
232 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
234 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
239 impl PartialEq for () {
241 fn eq(&self, _other: &()) -> bool { true }
243 fn ne(&self, _other: &()) -> bool { false }
246 eq_impl!(bool char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
248 macro_rules! totaleq_impl(
254 totaleq_impl!(() bool char uint u8 u16 u32 u64 int i8 i16 i32 i64)
256 macro_rules! ord_impl(
258 impl PartialOrd for $t {
260 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
261 match (self <= other, self >= other) {
262 (false, false) => None,
263 (false, true) => Some(Greater),
264 (true, false) => Some(Less),
265 (true, true) => Some(Equal),
269 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
271 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
273 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
275 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
280 impl PartialOrd for () {
282 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
287 impl PartialOrd for bool {
289 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
290 (*self as u8).partial_cmp(&(*other as u8))
294 ord_impl!(char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
296 macro_rules! totalord_impl(
300 fn cmp(&self, other: &$t) -> Ordering {
301 if *self < *other { Less }
302 else if *self > *other { Greater }
311 fn cmp(&self, _other: &()) -> Ordering { Equal }
316 fn cmp(&self, other: &bool) -> Ordering {
317 (*self as u8).cmp(&(*other as u8))
321 totalord_impl!(char uint u8 u16 u32 u64 int i8 i16 i32 i64)
324 impl<'a, T: PartialEq> PartialEq for &'a T {
326 fn eq(&self, other: & &'a T) -> bool { *(*self) == *(*other) }
328 fn ne(&self, other: & &'a T) -> bool { *(*self) != *(*other) }
330 impl<'a, T: PartialOrd> PartialOrd for &'a T {
332 fn partial_cmp(&self, other: &&'a T) -> Option<Ordering> {
333 (**self).partial_cmp(*other)
336 fn lt(&self, other: & &'a T) -> bool { *(*self) < *(*other) }
338 fn le(&self, other: & &'a T) -> bool { *(*self) <= *(*other) }
340 fn ge(&self, other: & &'a T) -> bool { *(*self) >= *(*other) }
342 fn gt(&self, other: & &'a T) -> bool { *(*self) > *(*other) }
344 impl<'a, T: Ord> Ord for &'a T {
346 fn cmp(&self, other: & &'a T) -> Ordering { (**self).cmp(*other) }
348 impl<'a, T: Eq> Eq for &'a T {}
351 impl<'a, T: PartialEq> PartialEq for &'a mut T {
353 fn eq(&self, other: &&'a mut T) -> bool { **self == *(*other) }
355 fn ne(&self, other: &&'a mut T) -> bool { **self != *(*other) }
357 impl<'a, T: PartialOrd> PartialOrd for &'a mut T {
359 fn partial_cmp(&self, other: &&'a mut T) -> Option<Ordering> {
360 (**self).partial_cmp(*other)
363 fn lt(&self, other: &&'a mut T) -> bool { **self < **other }
365 fn le(&self, other: &&'a mut T) -> bool { **self <= **other }
367 fn ge(&self, other: &&'a mut T) -> bool { **self >= **other }
369 fn gt(&self, other: &&'a mut T) -> bool { **self > **other }
371 impl<'a, T: Ord> Ord for &'a mut T {
373 fn cmp(&self, other: &&'a mut T) -> Ordering { (**self).cmp(*other) }
375 impl<'a, T: Eq> Eq for &'a mut T {}