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 `Ord` and `Eq` comparison traits.
13 //! This module defines both `Ord` and `Eq` traits which are used by the
14 //! compiler to implement comparison operators. Rust programs may implement
15 //!`Ord` to overload the `<`, `<=`, `>`, and `>=` operators, and may implement
16 //! `Eq` to overload the `==` and `!=` operators.
18 //! For example, to define a type with a customized definition for the Eq
19 //! operators, you could do the following:
23 //! struct SketchyNum {
27 //! // Our implementation of `Eq` to support `==` and `!=`.
28 //! impl Eq 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 pub use PartialEq = cmp::Eq;
41 pub use PartialOrd = cmp::Ord;
43 /// Trait for values that can be compared for equality and inequality.
45 /// This trait allows partial equality, where types can be unordered instead of
46 /// strictly equal or unequal. For example, with the built-in floating-point
47 /// types `a == b` and `a != b` will both evaluate to false if either `a` or
48 /// `b` is NaN (cf. IEEE 754-2008 section 5.11).
50 /// Eq only requires the `eq` method to be implemented; `ne` is its negation by
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 TotalEq: Eq {
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, Eq, 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 TotalOrd: TotalEq + Ord {
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 TotalEq for Ordering {}
123 impl TotalOrd for Ordering {
125 fn cmp(&self, other: &Ordering) -> Ordering {
126 (*self as int).cmp(&(*other as int))
130 impl Ord for Ordering {
132 fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
135 /// Combine orderings, lexically.
137 /// For example for a type `(int, int)`, two comparisons could be done.
138 /// If the first ordering is different, the first ordering is all that must be returned.
139 /// If the first ordering is equal, then second ordering is returned.
141 pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
148 /// Trait for values that can be compared for a sort-order.
150 /// Ord only requires implementation of the `lt` method,
151 /// with the others generated from default implementations.
153 /// However it remains possible to implement the others separately,
154 /// for compatibility with floating-point NaN semantics
155 /// (cf. IEEE 754-2008 section 5.11).
158 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
159 fn lt(&self, other: &Self) -> bool;
161 /// This method tests less than or equal to (`<=`).
163 fn le(&self, other: &Self) -> bool { !other.lt(self) }
165 /// This method tests greater than (`>`).
167 fn gt(&self, other: &Self) -> bool { other.lt(self) }
169 /// This method tests greater than or equal to (`>=`).
171 fn ge(&self, other: &Self) -> bool { !self.lt(other) }
174 /// The equivalence relation. Two values may be equivalent even if they are
175 /// of different types. The most common use case for this relation is
176 /// container types; e.g. it is often desirable to be able to use `&str`
177 /// values to look up entries in a container with `String` keys.
179 /// Implement this function to decide equivalent values.
180 fn equiv(&self, other: &T) -> bool;
183 /// Compare and return the minimum of two values.
185 pub fn min<T: TotalOrd>(v1: T, v2: T) -> T {
186 if v1 < v2 { v1 } else { v2 }
189 /// Compare and return the maximum of two values.
191 pub fn max<T: TotalOrd>(v1: T, v2: T) -> T {
192 if v1 > v2 { v1 } else { v2 }
195 // Implementation of Eq, TotalEq, Ord and TotalOrd for primitive types
198 use cmp::{Ord, TotalOrd, Eq, TotalEq, Ordering, Less, Greater, Equal};
200 macro_rules! eq_impl(
204 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
206 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
213 fn eq(&self, _other: &()) -> bool { true }
215 fn ne(&self, _other: &()) -> bool { false }
218 eq_impl!(bool char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
220 macro_rules! totaleq_impl(
222 impl TotalEq for $t {}
226 totaleq_impl!(() bool char uint u8 u16 u32 u64 int i8 i16 i32 i64)
228 macro_rules! ord_impl(
232 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
234 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
236 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
238 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
245 fn lt(&self, _other: &()) -> bool { false }
250 fn lt(&self, other: &bool) -> bool {
251 (*self as u8) < (*other as u8)
255 ord_impl!(char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
257 macro_rules! totalord_impl(
259 impl TotalOrd for $t {
261 fn cmp(&self, other: &$t) -> Ordering {
262 if *self < *other { Less }
263 else if *self > *other { Greater }
270 impl TotalOrd for () {
272 fn cmp(&self, _other: &()) -> Ordering { Equal }
275 impl TotalOrd for bool {
277 fn cmp(&self, other: &bool) -> Ordering {
278 (*self as u8).cmp(&(*other as u8))
282 totalord_impl!(char uint u8 u16 u32 u64 int i8 i16 i32 i64)
285 impl<'a, T: Eq> Eq for &'a T {
287 fn eq(&self, other: & &'a T) -> bool { *(*self) == *(*other) }
289 fn ne(&self, other: & &'a T) -> bool { *(*self) != *(*other) }
291 impl<'a, T: Ord> Ord for &'a T {
293 fn lt(&self, other: & &'a T) -> bool { *(*self) < *(*other) }
295 fn le(&self, other: & &'a T) -> bool { *(*self) <= *(*other) }
297 fn ge(&self, other: & &'a T) -> bool { *(*self) >= *(*other) }
299 fn gt(&self, other: & &'a T) -> bool { *(*self) > *(*other) }
301 impl<'a, T: TotalOrd> TotalOrd for &'a T {
303 fn cmp(&self, other: & &'a T) -> Ordering { (**self).cmp(*other) }
305 impl<'a, T: TotalEq> TotalEq for &'a T {}
308 impl<'a, T: Eq> Eq for &'a mut T {
310 fn eq(&self, other: &&'a mut T) -> bool { **self == *(*other) }
312 fn ne(&self, other: &&'a mut T) -> bool { **self != *(*other) }
314 impl<'a, T: Ord> Ord for &'a mut T {
316 fn lt(&self, other: &&'a mut T) -> bool { **self < **other }
318 fn le(&self, other: &&'a mut T) -> bool { **self <= **other }
320 fn ge(&self, other: &&'a mut T) -> bool { **self >= **other }
322 fn gt(&self, other: &&'a mut T) -> bool { **self > **other }
324 impl<'a, T: TotalOrd> TotalOrd for &'a mut T {
326 fn cmp(&self, other: &&'a mut T) -> Ordering { (**self).cmp(*other) }
328 impl<'a, T: TotalEq> TotalEq for &'a mut T {}
331 impl<T:Eq> Eq for @T {
333 fn eq(&self, other: &@T) -> bool { *(*self) == *(*other) }
335 fn ne(&self, other: &@T) -> bool { *(*self) != *(*other) }
337 impl<T:Ord> Ord for @T {
339 fn lt(&self, other: &@T) -> bool { *(*self) < *(*other) }
341 fn le(&self, other: &@T) -> bool { *(*self) <= *(*other) }
343 fn ge(&self, other: &@T) -> bool { *(*self) >= *(*other) }
345 fn gt(&self, other: &@T) -> bool { *(*self) > *(*other) }
347 impl<T: TotalOrd> TotalOrd for @T {
349 fn cmp(&self, other: &@T) -> Ordering { (**self).cmp(*other) }
351 impl<T: TotalEq> TotalEq for @T {}
356 use super::lexical_ordering;
359 fn test_int_totalord() {
360 assert_eq!(5u.cmp(&10), Less);
361 assert_eq!(10u.cmp(&5), Greater);
362 assert_eq!(5u.cmp(&5), Equal);
363 assert_eq!((-5u).cmp(&12), Less);
364 assert_eq!(12u.cmp(-5), Greater);
368 fn test_mut_int_totalord() {
369 assert_eq!((&mut 5u).cmp(&10), Less);
370 assert_eq!((&mut 10u).cmp(&5), Greater);
371 assert_eq!((&mut 5u).cmp(&5), Equal);
372 assert_eq!((&mut -5u).cmp(&12), Less);
373 assert_eq!((&mut 12u).cmp(-5), Greater);
377 fn test_ordering_order() {
378 assert!(Less < Equal);
379 assert_eq!(Greater.cmp(&Less), Greater);
383 fn test_lexical_ordering() {
384 fn t(o1: Ordering, o2: Ordering, e: Ordering) {
385 assert_eq!(lexical_ordering(o1, o2), e);
388 let xs = [Less, Equal, Greater];
389 for &o in xs.iter() {
392 t(Greater, o, Greater);
397 fn test_user_defined_eq() {
403 // Our implementation of `Eq` to support `==` and `!=`.
404 impl Eq for SketchyNum {
405 // Our custom eq allows numbers which are near each other to be equal! :D
406 fn eq(&self, other: &SketchyNum) -> bool {
407 (self.num - other.num).abs() < 5
411 // Now these binary operators will work when applied!
412 assert!(SketchyNum {num: 37} == SketchyNum {num: 34});
413 assert!(SketchyNum {num: 25} != SketchyNum {num: 57});