]> git.lizzy.rs Git - rust.git/blob - src/libstd/cmp.rs
610b9b63d80289e5bc3d7f634b368f81651a7e37
[rust.git] / src / libstd / cmp.rs
1 // Copyright 2012-2013 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.
4 //
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.
10
11 /*!
12
13 Defines the `Ord` and `Eq` comparison traits.
14
15 This module defines both `Ord` and `Eq` traits which are used by the compiler
16 to implement comparison operators.
17 Rust programs may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators,
18 and may implement `Eq` to overload the `==` and `!=` operators.
19
20 For example, to define a type with a customized definition for the Eq operators,
21 you could do the following:
22
23 ```rust
24 // Our type.
25 struct SketchyNum {
26     num : int
27 }
28
29 // Our implementation of `Eq` to support `==` and `!=`.
30 impl Eq for SketchyNum {
31     // Our custom eq allows numbers which are near eachother to be equal! :D
32     fn eq(&self, other: &SketchyNum) -> bool {
33         (self.num - other.num).abs() < 5
34     }
35 }
36
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});
40 ```
41
42 */
43
44 /**
45 * Trait for values that can be compared for equality and inequality.
46 *
47 * This trait allows partial equality, where types can be unordered instead of strictly equal or
48 * unequal. For example, with the built-in floating-point types `a == b` and `a != b` will both
49 * evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11).
50 *
51 * Eq only requires the `eq` method to be implemented; `ne` is its negation by default.
52 *
53 * Eventually, this will be implemented by default for types that implement `TotalEq`.
54 */
55 #[lang="eq"]
56 pub trait Eq {
57     /// This method tests for `self` and `other` values to be equal, and is used by `==`.
58     fn eq(&self, other: &Self) -> bool;
59
60     /// This method tests for `!=`.
61     #[inline]
62     fn ne(&self, other: &Self) -> bool { !self.eq(other) }
63 }
64
65 /**
66  * Trait for equality comparisons which are [equivalence relations](
67  * https://en.wikipedia.org/wiki/Equivalence_relation).
68  *
69  * This means, that in addition to `a == b` and `a != b` being strict inverses,
70  * the equality must be (for all `a`, `b` and `c`):
71  *
72  * - reflexive: `a == a`;
73  * - symmetric: `a == b` implies `b == a`; and
74  * - transitive: `a == b` and `b == c` implies `a == c`.
75  */
76
77 pub trait TotalEq: Eq {
78     // FIXME #13101: this method is used solely by #[deriving] to
79     // assert that every component of a type implements #[deriving]
80     // itself, the current deriving infrastructure means doing this
81     // assertion without using a method on this trait is nearly
82     // impossible.
83     //
84     // This should never be implemented by hand.
85     #[doc(hidden)]
86     #[inline(always)]
87     fn assert_receiver_is_total_eq(&self) {}
88 }
89
90 /// A macro which defines an implementation of TotalEq for a given type.
91 macro_rules! totaleq_impl(
92     ($t:ty) => {
93         impl TotalEq for $t {}
94     }
95 )
96
97 totaleq_impl!(bool)
98
99 totaleq_impl!(u8)
100 totaleq_impl!(u16)
101 totaleq_impl!(u32)
102 totaleq_impl!(u64)
103
104 totaleq_impl!(i8)
105 totaleq_impl!(i16)
106 totaleq_impl!(i32)
107 totaleq_impl!(i64)
108
109 totaleq_impl!(int)
110 totaleq_impl!(uint)
111
112 totaleq_impl!(char)
113
114 /// An ordering is, e.g, a result of a comparison between two values.
115 #[deriving(Clone, Eq, Show)]
116 pub enum Ordering {
117    /// An ordering where a compared value is less [than another].
118    Less = -1,
119    /// An ordering where a compared value is equal [to another].
120    Equal = 0,
121    /// An ordering where a compared value is greater [than another].
122    Greater = 1
123 }
124
125 /**
126  * Trait for types that form a [total order](
127  * https://en.wikipedia.org/wiki/Total_order).
128  *
129  * An order is a total order if it is (for all `a`, `b` and `c`):
130  *
131  * - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b`
132  *   is true; and
133  * - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for
134  *   both `==` and `>`.
135  */
136 pub trait TotalOrd: TotalEq + Ord {
137     /// This method returns an ordering between `self` and `other` values.
138     ///
139     /// By convention, `self.cmp(&other)` returns the ordering matching
140     /// the expression `self <operator> other` if true.  For example:
141     ///
142     /// ```
143     /// assert_eq!( 5u.cmp(&10), Less);     // because 5 < 10
144     /// assert_eq!(10u.cmp(&5),  Greater);  // because 10 > 5
145     /// assert_eq!( 5u.cmp(&5),  Equal);    // because 5 == 5
146     /// ```
147     fn cmp(&self, other: &Self) -> Ordering;
148 }
149
150 impl TotalEq for Ordering {}
151 impl TotalOrd for Ordering {
152     #[inline]
153     fn cmp(&self, other: &Ordering) -> Ordering {
154         (*self as int).cmp(&(*other as int))
155     }
156 }
157
158 impl Ord for Ordering {
159     #[inline]
160     fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
161 }
162
163 /// A macro which defines an implementation of TotalOrd for a given type.
164 macro_rules! totalord_impl(
165     ($t:ty) => {
166         impl TotalOrd for $t {
167             #[inline]
168             fn cmp(&self, other: &$t) -> Ordering {
169                 if *self < *other { Less }
170                 else if *self > *other { Greater }
171                 else { Equal }
172             }
173         }
174     }
175 )
176
177 totalord_impl!(u8)
178 totalord_impl!(u16)
179 totalord_impl!(u32)
180 totalord_impl!(u64)
181
182 totalord_impl!(i8)
183 totalord_impl!(i16)
184 totalord_impl!(i32)
185 totalord_impl!(i64)
186
187 totalord_impl!(int)
188 totalord_impl!(uint)
189
190 totalord_impl!(char)
191
192 /**
193  * Combine orderings, lexically.
194  *
195  * For example for a type `(int, int)`, two comparisons could be done.
196  * If the first ordering is different, the first ordering is all that must be returned.
197  * If the first ordering is equal, then second ordering is returned.
198 */
199 #[inline]
200 pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
201     match o1 {
202         Equal => o2,
203         _ => o1
204     }
205 }
206
207 /**
208 * Trait for values that can be compared for a sort-order.
209 *
210 * Ord only requires implementation of the `lt` method,
211 * with the others generated from default implementations.
212 *
213 * However it remains possible to implement the others separately,
214 * for compatibility with floating-point NaN semantics
215 * (cf. IEEE 754-2008 section 5.11).
216 */
217 #[lang="ord"]
218 pub trait Ord: Eq {
219     /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
220     fn lt(&self, other: &Self) -> bool;
221
222     /// This method tests less than or equal to (`<=`).
223     #[inline]
224     fn le(&self, other: &Self) -> bool { !other.lt(self) }
225
226     /// This method tests greater than (`>`).
227     #[inline]
228     fn gt(&self, other: &Self) -> bool {  other.lt(self) }
229
230     /// This method tests greater than or equal to (`>=`).
231     #[inline]
232     fn ge(&self, other: &Self) -> bool { !self.lt(other) }
233 }
234
235 /// The equivalence relation. Two values may be equivalent even if they are
236 /// of different types. The most common use case for this relation is
237 /// container types; e.g. it is often desirable to be able to use `&str`
238 /// values to look up entries in a container with `~str` keys.
239 pub trait Equiv<T> {
240     /// Implement this function to decide equivalent values.
241     fn equiv(&self, other: &T) -> bool;
242 }
243
244 /// Compare and return the minimum of two values.
245 #[inline]
246 pub fn min<T: TotalOrd>(v1: T, v2: T) -> T {
247     if v1 < v2 { v1 } else { v2 }
248 }
249
250 /// Compare and return the maximum of two values.
251 #[inline]
252 pub fn max<T: TotalOrd>(v1: T, v2: T) -> T {
253     if v1 > v2 { v1 } else { v2 }
254 }
255
256 #[cfg(test)]
257 mod test {
258     use super::lexical_ordering;
259
260     #[test]
261     fn test_int_totalord() {
262         assert_eq!(5u.cmp(&10), Less);
263         assert_eq!(10u.cmp(&5), Greater);
264         assert_eq!(5u.cmp(&5), Equal);
265         assert_eq!((-5u).cmp(&12), Less);
266         assert_eq!(12u.cmp(-5), Greater);
267     }
268
269     #[test]
270     fn test_ordering_order() {
271         assert!(Less < Equal);
272         assert_eq!(Greater.cmp(&Less), Greater);
273     }
274
275     #[test]
276     fn test_lexical_ordering() {
277         fn t(o1: Ordering, o2: Ordering, e: Ordering) {
278             assert_eq!(lexical_ordering(o1, o2), e);
279         }
280
281         let xs = [Less, Equal, Greater];
282         for &o in xs.iter() {
283             t(Less, o, Less);
284             t(Equal, o, o);
285             t(Greater, o, Greater);
286          }
287     }
288
289     #[test]
290     fn test_user_defined_eq() {
291         // Our type.
292         struct SketchyNum {
293             num : int
294         }
295
296         // Our implementation of `Eq` to support `==` and `!=`.
297         impl Eq for SketchyNum {
298             // Our custom eq allows numbers which are near eachother to be equal! :D
299             fn eq(&self, other: &SketchyNum) -> bool {
300                 (self.num - other.num).abs() < 5
301             }
302         }
303
304         // Now these binary operators will work when applied!
305         assert!(SketchyNum {num: 37} == SketchyNum {num: 34});
306         assert!(SketchyNum {num: 25} != SketchyNum {num: 57});
307     }
308 }