]> git.proxmox.com Git - rustc.git/blob - src/libcore/cmp.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / libcore / cmp.rs
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.
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 //! Functionality for ordering and comparison.
12 //!
13 //! This module defines both `PartialOrd` and `PartialEq` traits which are used
14 //! by the compiler to implement comparison operators. Rust programs may
15 //! implement `PartialOrd` to overload the `<`, `<=`, `>`, and `>=` operators,
16 //! and may implement `PartialEq` to overload the `==` and `!=` operators.
17 //!
18 //! # Examples
19 //!
20 //! ```
21 //! let x: u32 = 0;
22 //! let y: u32 = 1;
23 //!
24 //! // these two lines are equivalent
25 //! assert_eq!(x < y, true);
26 //! assert_eq!(x.lt(&y), true);
27 //!
28 //! // these two lines are also equivalent
29 //! assert_eq!(x == y, false);
30 //! assert_eq!(x.eq(&y), false);
31 //! ```
32
33 #![stable(feature = "rust1", since = "1.0.0")]
34
35 use self::Ordering::*;
36
37 use marker::Sized;
38 use option::Option::{self, Some};
39
40 /// Trait for equality comparisons which are [partial equivalence
41 /// relations](http://en.wikipedia.org/wiki/Partial_equivalence_relation).
42 ///
43 /// This trait allows for partial equality, for types that do not have a full
44 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
45 /// so floating point types implement `PartialEq` but not `Eq`.
46 ///
47 /// Formally, the equality must be (for all `a`, `b` and `c`):
48 ///
49 /// - symmetric: `a == b` implies `b == a`; and
50 /// - transitive: `a == b` and `b == c` implies `a == c`.
51 ///
52 /// Note that these requirements mean that the trait itself must be implemented
53 /// symmetrically and transitively: if `T: PartialEq<U>` and `U: PartialEq<V>`
54 /// then `U: PartialEq<T>` and `T: PartialEq<V>`.
55 ///
56 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined
57 /// in terms of it by default. Any manual implementation of `ne` *must* respect
58 /// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
59 /// only if `a != b`.
60 ///
61 /// This trait can be used with `#[derive]`.
62 ///
63 /// # Examples
64 ///
65 /// ```
66 /// let x: u32 = 0;
67 /// let y: u32 = 1;
68 ///
69 /// assert_eq!(x == y, false);
70 /// assert_eq!(x.eq(&y), false);
71 /// ```
72 #[lang = "eq"]
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub trait PartialEq<Rhs: ?Sized = Self> {
75 /// This method tests for `self` and `other` values to be equal, and is used
76 /// by `==`.
77 #[stable(feature = "rust1", since = "1.0.0")]
78 fn eq(&self, other: &Rhs) -> bool;
79
80 /// This method tests for `!=`.
81 #[inline]
82 #[stable(feature = "rust1", since = "1.0.0")]
83 fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
84 }
85
86 /// Trait for equality comparisons which are [equivalence relations](
87 /// https://en.wikipedia.org/wiki/Equivalence_relation).
88 ///
89 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
90 /// be (for all `a`, `b` and `c`):
91 ///
92 /// - reflexive: `a == a`;
93 /// - symmetric: `a == b` implies `b == a`; and
94 /// - transitive: `a == b` and `b == c` implies `a == c`.
95 ///
96 /// This property cannot be checked by the compiler, and therefore `Eq` implies
97 /// `PartialEq`, and has no extra methods.
98 ///
99 /// This trait can be used with `#[derive]`.
100 #[stable(feature = "rust1", since = "1.0.0")]
101 pub trait Eq: PartialEq<Self> {
102 // FIXME #13101: this method is used solely by #[deriving] to
103 // assert that every component of a type implements #[deriving]
104 // itself, the current deriving infrastructure means doing this
105 // assertion without using a method on this trait is nearly
106 // impossible.
107 //
108 // This should never be implemented by hand.
109 #[doc(hidden)]
110 #[inline(always)]
111 #[stable(feature = "rust1", since = "1.0.0")]
112 fn assert_receiver_is_total_eq(&self) {}
113 }
114
115 /// An `Ordering` is the result of a comparison between two values.
116 ///
117 /// # Examples
118 ///
119 /// ```
120 /// use std::cmp::Ordering;
121 ///
122 /// let result = 1.cmp(&2);
123 /// assert_eq!(Ordering::Less, result);
124 ///
125 /// let result = 1.cmp(&1);
126 /// assert_eq!(Ordering::Equal, result);
127 ///
128 /// let result = 2.cmp(&1);
129 /// assert_eq!(Ordering::Greater, result);
130 /// ```
131 #[derive(Clone, Copy, PartialEq, Debug)]
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub enum Ordering {
134 /// An ordering where a compared value is less [than another].
135 #[stable(feature = "rust1", since = "1.0.0")]
136 Less = -1,
137 /// An ordering where a compared value is equal [to another].
138 #[stable(feature = "rust1", since = "1.0.0")]
139 Equal = 0,
140 /// An ordering where a compared value is greater [than another].
141 #[stable(feature = "rust1", since = "1.0.0")]
142 Greater = 1,
143 }
144
145 impl Ordering {
146 /// Reverse the `Ordering`.
147 ///
148 /// * `Less` becomes `Greater`.
149 /// * `Greater` becomes `Less`.
150 /// * `Equal` becomes `Equal`.
151 ///
152 /// # Examples
153 ///
154 /// Basic behavior:
155 ///
156 /// ```
157 /// use std::cmp::Ordering;
158 ///
159 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
160 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
161 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
162 /// ```
163 ///
164 /// This method can be used to reverse a comparison:
165 ///
166 /// ```
167 /// let mut data: &mut [_] = &mut [2, 10, 5, 8];
168 ///
169 /// // sort the array from largest to smallest.
170 /// data.sort_by(|a, b| a.cmp(b).reverse());
171 ///
172 /// let b: &mut [_] = &mut [10, 8, 5, 2];
173 /// assert!(data == b);
174 /// ```
175 #[inline]
176 #[stable(feature = "rust1", since = "1.0.0")]
177 pub fn reverse(self) -> Ordering {
178 match self {
179 Less => Greater,
180 Equal => Equal,
181 Greater => Less,
182 }
183 }
184 }
185
186 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
187 ///
188 /// An order is a total order if it is (for all `a`, `b` and `c`):
189 ///
190 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
191 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
192 ///
193 /// This trait can be used with `#[derive]`. When `derive`d, it will produce a lexicographic
194 /// ordering based on the top-to-bottom declaration order of the struct's members.
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub trait Ord: Eq + PartialOrd<Self> {
197 /// This method returns an `Ordering` between `self` and `other`.
198 ///
199 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
200 /// `self <operator> other` if true.
201 ///
202 /// # Examples
203 ///
204 /// ```
205 /// use std::cmp::Ordering;
206 ///
207 /// assert_eq!(5.cmp(&10), Ordering::Less);
208 /// assert_eq!(10.cmp(&5), Ordering::Greater);
209 /// assert_eq!(5.cmp(&5), Ordering::Equal);
210 /// ```
211 #[stable(feature = "rust1", since = "1.0.0")]
212 fn cmp(&self, other: &Self) -> Ordering;
213 }
214
215 #[stable(feature = "rust1", since = "1.0.0")]
216 impl Eq for Ordering {}
217
218 #[stable(feature = "rust1", since = "1.0.0")]
219 impl Ord for Ordering {
220 #[inline]
221 fn cmp(&self, other: &Ordering) -> Ordering {
222 (*self as i32).cmp(&(*other as i32))
223 }
224 }
225
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl PartialOrd for Ordering {
228 #[inline]
229 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
230 (*self as i32).partial_cmp(&(*other as i32))
231 }
232 }
233
234 /// Trait for values that can be compared for a sort-order.
235 ///
236 /// The comparison must satisfy, for all `a`, `b` and `c`:
237 ///
238 /// - antisymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
239 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
240 ///
241 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
242 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
243 /// PartialOrd<V>`.
244 ///
245 /// PartialOrd only requires implementation of the `partial_cmp` method, with the others generated
246 /// from default implementations.
247 ///
248 /// However it remains possible to implement the others separately for types which do not have a
249 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
250 /// false` (cf. IEEE 754-2008 section 5.11).
251 ///
252 /// This trait can be used with `#[derive]`. When `derive`d, it will produce an ordering
253 /// based on the top-to-bottom declaration order of the struct's members.
254 ///
255 /// # Examples
256 ///
257 /// ```
258 /// let x : u32 = 0;
259 /// let y : u32 = 1;
260 ///
261 /// assert_eq!(x < y, true);
262 /// assert_eq!(x.lt(&y), true);
263 /// ```
264 #[lang = "ord"]
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
267 /// This method returns an ordering between `self` and `other` values if one exists.
268 ///
269 /// # Examples
270 ///
271 /// ```
272 /// use std::cmp::Ordering;
273 ///
274 /// let result = 1.0.partial_cmp(&2.0);
275 /// assert_eq!(result, Some(Ordering::Less));
276 ///
277 /// let result = 1.0.partial_cmp(&1.0);
278 /// assert_eq!(result, Some(Ordering::Equal));
279 ///
280 /// let result = 2.0.partial_cmp(&1.0);
281 /// assert_eq!(result, Some(Ordering::Greater));
282 /// ```
283 ///
284 /// When comparison is impossible:
285 ///
286 /// ```
287 /// let result = std::f64::NAN.partial_cmp(&1.0);
288 /// assert_eq!(result, None);
289 /// ```
290 #[stable(feature = "rust1", since = "1.0.0")]
291 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
292
293 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
294 ///
295 /// # Examples
296 ///
297 /// ```
298 /// let result = 1.0 < 2.0;
299 /// assert_eq!(result, true);
300 ///
301 /// let result = 2.0 < 1.0;
302 /// assert_eq!(result, false);
303 /// ```
304 #[inline]
305 #[stable(feature = "rust1", since = "1.0.0")]
306 fn lt(&self, other: &Rhs) -> bool {
307 match self.partial_cmp(other) {
308 Some(Less) => true,
309 _ => false,
310 }
311 }
312
313 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
314 /// operator.
315 ///
316 /// # Examples
317 ///
318 /// ```
319 /// let result = 1.0 <= 2.0;
320 /// assert_eq!(result, true);
321 ///
322 /// let result = 2.0 <= 2.0;
323 /// assert_eq!(result, true);
324 /// ```
325 #[inline]
326 #[stable(feature = "rust1", since = "1.0.0")]
327 fn le(&self, other: &Rhs) -> bool {
328 match self.partial_cmp(other) {
329 Some(Less) | Some(Equal) => true,
330 _ => false,
331 }
332 }
333
334 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// let result = 1.0 > 2.0;
340 /// assert_eq!(result, false);
341 ///
342 /// let result = 2.0 > 2.0;
343 /// assert_eq!(result, false);
344 /// ```
345 #[inline]
346 #[stable(feature = "rust1", since = "1.0.0")]
347 fn gt(&self, other: &Rhs) -> bool {
348 match self.partial_cmp(other) {
349 Some(Greater) => true,
350 _ => false,
351 }
352 }
353
354 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
355 /// operator.
356 ///
357 /// # Examples
358 ///
359 /// ```
360 /// let result = 2.0 >= 1.0;
361 /// assert_eq!(result, true);
362 ///
363 /// let result = 2.0 >= 2.0;
364 /// assert_eq!(result, true);
365 /// ```
366 #[inline]
367 #[stable(feature = "rust1", since = "1.0.0")]
368 fn ge(&self, other: &Rhs) -> bool {
369 match self.partial_cmp(other) {
370 Some(Greater) | Some(Equal) => true,
371 _ => false,
372 }
373 }
374 }
375
376 /// Compare and return the minimum of two values.
377 ///
378 /// Returns the first argument if the comparison determines them to be equal.
379 ///
380 /// # Examples
381 ///
382 /// ```
383 /// use std::cmp;
384 ///
385 /// assert_eq!(1, cmp::min(1, 2));
386 /// assert_eq!(2, cmp::min(2, 2));
387 /// ```
388 #[inline]
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn min<T: Ord>(v1: T, v2: T) -> T {
391 if v1 <= v2 { v1 } else { v2 }
392 }
393
394 /// Compare and return the maximum of two values.
395 ///
396 /// Returns the second argument if the comparison determines them to be equal.
397 ///
398 /// # Examples
399 ///
400 /// ```
401 /// use std::cmp;
402 ///
403 /// assert_eq!(2, cmp::max(1, 2));
404 /// assert_eq!(2, cmp::max(2, 2));
405 /// ```
406 #[inline]
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn max<T: Ord>(v1: T, v2: T) -> T {
409 if v2 >= v1 { v2 } else { v1 }
410 }
411
412 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
413 mod impls {
414 use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering};
415 use cmp::Ordering::{Less, Greater, Equal};
416 use marker::Sized;
417 use option::Option;
418 use option::Option::{Some, None};
419
420 macro_rules! partial_eq_impl {
421 ($($t:ty)*) => ($(
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl PartialEq for $t {
424 #[inline]
425 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
426 #[inline]
427 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
428 }
429 )*)
430 }
431
432 #[stable(feature = "rust1", since = "1.0.0")]
433 impl PartialEq for () {
434 #[inline]
435 fn eq(&self, _other: &()) -> bool { true }
436 #[inline]
437 fn ne(&self, _other: &()) -> bool { false }
438 }
439
440 partial_eq_impl! {
441 bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64
442 }
443
444 macro_rules! eq_impl {
445 ($($t:ty)*) => ($(
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl Eq for $t {}
448 )*)
449 }
450
451 eq_impl! { () bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
452
453 macro_rules! partial_ord_impl {
454 ($($t:ty)*) => ($(
455 #[stable(feature = "rust1", since = "1.0.0")]
456 impl PartialOrd for $t {
457 #[inline]
458 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
459 match (self <= other, self >= other) {
460 (false, false) => None,
461 (false, true) => Some(Greater),
462 (true, false) => Some(Less),
463 (true, true) => Some(Equal),
464 }
465 }
466 #[inline]
467 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
468 #[inline]
469 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
470 #[inline]
471 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
472 #[inline]
473 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
474 }
475 )*)
476 }
477
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl PartialOrd for () {
480 #[inline]
481 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
482 Some(Equal)
483 }
484 }
485
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl PartialOrd for bool {
488 #[inline]
489 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
490 (*self as u8).partial_cmp(&(*other as u8))
491 }
492 }
493
494 partial_ord_impl! { f32 f64 }
495
496 macro_rules! ord_impl {
497 ($($t:ty)*) => ($(
498 #[stable(feature = "rust1", since = "1.0.0")]
499 impl PartialOrd for $t {
500 #[inline]
501 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
502 Some(self.cmp(other))
503 }
504 #[inline]
505 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
506 #[inline]
507 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
508 #[inline]
509 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
510 #[inline]
511 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
512 }
513
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl Ord for $t {
516 #[inline]
517 fn cmp(&self, other: &$t) -> Ordering {
518 if *self == *other { Equal }
519 else if *self < *other { Less }
520 else { Greater }
521 }
522 }
523 )*)
524 }
525
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl Ord for () {
528 #[inline]
529 fn cmp(&self, _other: &()) -> Ordering { Equal }
530 }
531
532 #[stable(feature = "rust1", since = "1.0.0")]
533 impl Ord for bool {
534 #[inline]
535 fn cmp(&self, other: &bool) -> Ordering {
536 (*self as u8).cmp(&(*other as u8))
537 }
538 }
539
540 ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
541
542 // & pointers
543
544 #[stable(feature = "rust1", since = "1.0.0")]
545 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a A where A: PartialEq<B> {
546 #[inline]
547 fn eq(&self, other: & &'b B) -> bool { PartialEq::eq(*self, *other) }
548 #[inline]
549 fn ne(&self, other: & &'b B) -> bool { PartialEq::ne(*self, *other) }
550 }
551 #[stable(feature = "rust1", since = "1.0.0")]
552 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b B> for &'a A where A: PartialOrd<B> {
553 #[inline]
554 fn partial_cmp(&self, other: &&'b B) -> Option<Ordering> {
555 PartialOrd::partial_cmp(*self, *other)
556 }
557 #[inline]
558 fn lt(&self, other: & &'b B) -> bool { PartialOrd::lt(*self, *other) }
559 #[inline]
560 fn le(&self, other: & &'b B) -> bool { PartialOrd::le(*self, *other) }
561 #[inline]
562 fn ge(&self, other: & &'b B) -> bool { PartialOrd::ge(*self, *other) }
563 #[inline]
564 fn gt(&self, other: & &'b B) -> bool { PartialOrd::gt(*self, *other) }
565 }
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl<'a, A: ?Sized> Ord for &'a A where A: Ord {
568 #[inline]
569 fn cmp(&self, other: & &'a A) -> Ordering { Ord::cmp(*self, *other) }
570 }
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl<'a, A: ?Sized> Eq for &'a A where A: Eq {}
573
574 // &mut pointers
575
576 #[stable(feature = "rust1", since = "1.0.0")]
577 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a mut A where A: PartialEq<B> {
578 #[inline]
579 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
580 #[inline]
581 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
582 }
583 #[stable(feature = "rust1", since = "1.0.0")]
584 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b mut B> for &'a mut A where A: PartialOrd<B> {
585 #[inline]
586 fn partial_cmp(&self, other: &&'b mut B) -> Option<Ordering> {
587 PartialOrd::partial_cmp(*self, *other)
588 }
589 #[inline]
590 fn lt(&self, other: &&'b mut B) -> bool { PartialOrd::lt(*self, *other) }
591 #[inline]
592 fn le(&self, other: &&'b mut B) -> bool { PartialOrd::le(*self, *other) }
593 #[inline]
594 fn ge(&self, other: &&'b mut B) -> bool { PartialOrd::ge(*self, *other) }
595 #[inline]
596 fn gt(&self, other: &&'b mut B) -> bool { PartialOrd::gt(*self, *other) }
597 }
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl<'a, A: ?Sized> Ord for &'a mut A where A: Ord {
600 #[inline]
601 fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
602 }
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl<'a, A: ?Sized> Eq for &'a mut A where A: Eq {}
605
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a A where A: PartialEq<B> {
608 #[inline]
609 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
610 #[inline]
611 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
612 }
613
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a mut A where A: PartialEq<B> {
616 #[inline]
617 fn eq(&self, other: &&'b B) -> bool { PartialEq::eq(*self, *other) }
618 #[inline]
619 fn ne(&self, other: &&'b B) -> bool { PartialEq::ne(*self, *other) }
620 }
621 }