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 //! Functionality for ordering and comparison.
13 //! This module defines both `PartialOrd` and `PartialEq` traits which are used by the compiler to
14 //! implement comparison operators. Rust programs may implement `PartialOrd` to overload the `<`,
15 //! `<=`, `>`, and `>=` operators, and may implement `PartialEq` to overload the `==` and `!=`
18 //! For example, to define a type with a customized definition for the PartialEq operators, you
19 //! could do the following:
22 //! use core::num::SignedInt;
28 //! impl PartialEq for FuzzyNum {
29 //! // Our custom eq allows numbers which are near each other to be equal! :D
30 //! fn eq(&self, other: &FuzzyNum) -> bool {
31 //! (self.num - other.num).abs() < 5
35 //! // Now these binary operators will work when applied!
36 //! assert!(FuzzyNum { num: 37 } == FuzzyNum { num: 34 });
37 //! assert!(FuzzyNum { num: 25 } != FuzzyNum { num: 57 });
40 #![stable(feature = "rust1", since = "1.0.0")]
42 use self::Ordering::*;
45 use option::Option::{self, Some, None};
47 /// Trait for equality comparisons which are [partial equivalence relations](
48 /// http://en.wikipedia.org/wiki/Partial_equivalence_relation).
50 /// This trait allows for partial equality, for types that do not have a full equivalence relation.
51 /// For example, in floating point numbers `NaN != NaN`, so floating point types implement
52 /// `PartialEq` but not `Eq`.
54 /// Formally, the equality must be (for all `a`, `b` and `c`):
56 /// - symmetric: `a == b` implies `b == a`; and
57 /// - transitive: `a == b` and `b == c` implies `a == c`.
59 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
60 /// transitively: if `T: PartialEq<U>` and `U: PartialEq<V>` then `U: PartialEq<T>` and `T:
63 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined in terms of it by
64 /// default. Any manual implementation of `ne` *must* respect the rule that `eq` is a strict
65 /// inverse of `ne`; that is, `!(a == b)` if and only if `a != b`.
67 #[stable(feature = "rust1", since = "1.0.0")]
69 pub trait PartialEq<Rhs: ?Sized = Self> {
70 /// This method tests for `self` and `other` values to be equal, and is used by `==`.
71 #[stable(feature = "rust1", since = "1.0.0")]
72 fn eq(&self, other: &Rhs) -> bool;
74 /// This method tests for `!=`.
76 #[stable(feature = "rust1", since = "1.0.0")]
77 fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
80 /// Trait for equality comparisons which are [equivalence relations](
81 /// https://en.wikipedia.org/wiki/Equivalence_relation).
83 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
84 /// be (for all `a`, `b` and `c`):
86 /// - reflexive: `a == a`;
87 /// - symmetric: `a == b` implies `b == a`; and
88 /// - transitive: `a == b` and `b == c` implies `a == c`.
90 /// This property cannot be checked by the compiler, and therefore `Eq` implies
91 /// `PartialEq`, and has no extra methods.
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub trait Eq: 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 #[stable(feature = "rust1", since = "1.0.0")]
104 fn assert_receiver_is_total_eq(&self) {}
107 /// An `Ordering` is the result of a comparison between two values.
112 /// use std::cmp::Ordering;
114 /// let result = 1.cmp(&2);
115 /// assert_eq!(Ordering::Less, result);
117 /// let result = 1.cmp(&1);
118 /// assert_eq!(Ordering::Equal, result);
120 /// let result = 2.cmp(&1);
121 /// assert_eq!(Ordering::Greater, result);
123 #[derive(Clone, Copy, PartialEq, Debug)]
124 #[stable(feature = "rust1", since = "1.0.0")]
126 /// An ordering where a compared value is less [than another].
127 #[stable(feature = "rust1", since = "1.0.0")]
129 /// An ordering where a compared value is equal [to another].
130 #[stable(feature = "rust1", since = "1.0.0")]
132 /// An ordering where a compared value is greater [than another].
133 #[stable(feature = "rust1", since = "1.0.0")]
138 /// Reverse the `Ordering`.
140 /// * `Less` becomes `Greater`.
141 /// * `Greater` becomes `Less`.
142 /// * `Equal` becomes `Equal`.
149 /// use std::cmp::Ordering;
151 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
152 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
153 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
156 /// This method can be used to reverse a comparison:
159 /// use std::cmp::Ordering;
161 /// let mut data: &mut [_] = &mut [2, 10, 5, 8];
163 /// // sort the array from largest to smallest.
164 /// data.sort_by(|a, b| a.cmp(b).reverse());
166 /// let b: &mut [_] = &mut [10, 8, 5, 2];
167 /// assert!(data == b);
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub fn reverse(self) -> Ordering {
173 // this compiles really nicely (to a single instruction);
174 // an explicit match has a pile of branches and
177 // NB. it is safe because of the explicit discriminants
179 ::mem::transmute::<_, Ordering>(-(self as i8))
184 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
186 /// An order is a total order if it is (for all `a`, `b` and `c`):
188 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
189 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub trait Ord: Eq + PartialOrd<Self> {
192 /// This method returns an `Ordering` between `self` and `other`.
194 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
195 /// `self <operator> other` if true.
200 /// use std::cmp::Ordering;
202 /// assert_eq!(5.cmp(&10), Ordering::Less);
203 /// assert_eq!(10.cmp(&5), Ordering::Greater);
204 /// assert_eq!(5.cmp(&5), Ordering::Equal);
206 #[stable(feature = "rust1", since = "1.0.0")]
207 fn cmp(&self, other: &Self) -> Ordering;
210 #[stable(feature = "rust1", since = "1.0.0")]
211 impl Eq for Ordering {}
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl Ord for Ordering {
216 #[stable(feature = "rust1", since = "1.0.0")]
217 fn cmp(&self, other: &Ordering) -> Ordering {
218 (*self as i32).cmp(&(*other as i32))
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl PartialOrd for Ordering {
225 #[stable(feature = "rust1", since = "1.0.0")]
226 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
227 (*self as i32).partial_cmp(&(*other as i32))
231 /// Trait for values that can be compared for a sort-order.
233 /// The comparison must satisfy, for all `a`, `b` and `c`:
235 /// - antisymmetry: if `a < b` then `!(a > b)` and vice versa; and
236 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
238 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
239 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
242 /// PartialOrd only requires implementation of the `partial_cmp` method, with the others generated
243 /// from default implementations.
245 /// However it remains possible to implement the others separately for types which do not have a
246 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
247 /// false` (cf. IEEE 754-2008 section 5.11).
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
251 /// This method returns an ordering between `self` and `other` values if one exists.
256 /// use std::cmp::Ordering;
258 /// let result = 1.0.partial_cmp(&2.0);
259 /// assert_eq!(result, Some(Ordering::Less));
261 /// let result = 1.0.partial_cmp(&1.0);
262 /// assert_eq!(result, Some(Ordering::Equal));
264 /// let result = 2.0.partial_cmp(&1.0);
265 /// assert_eq!(result, Some(Ordering::Greater));
268 /// When comparison is impossible:
271 /// let result = std::f64::NAN.partial_cmp(&1.0);
272 /// assert_eq!(result, None);
274 #[stable(feature = "rust1", since = "1.0.0")]
275 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
277 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
282 /// use std::cmp::Ordering;
284 /// let result = 1.0 < 2.0;
285 /// assert_eq!(result, true);
287 /// let result = 2.0 < 1.0;
288 /// assert_eq!(result, false);
291 #[stable(feature = "rust1", since = "1.0.0")]
292 fn lt(&self, other: &Rhs) -> bool {
293 match self.partial_cmp(other) {
299 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
305 /// let result = 1.0 <= 2.0;
306 /// assert_eq!(result, true);
308 /// let result = 2.0 <= 2.0;
309 /// assert_eq!(result, true);
312 #[stable(feature = "rust1", since = "1.0.0")]
313 fn le(&self, other: &Rhs) -> bool {
314 match self.partial_cmp(other) {
315 Some(Less) | Some(Equal) => true,
320 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
325 /// let result = 1.0 > 2.0;
326 /// assert_eq!(result, false);
328 /// let result = 2.0 > 2.0;
329 /// assert_eq!(result, false);
332 #[stable(feature = "rust1", since = "1.0.0")]
333 fn gt(&self, other: &Rhs) -> bool {
334 match self.partial_cmp(other) {
335 Some(Greater) => true,
340 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
346 /// let result = 2.0 >= 1.0;
347 /// assert_eq!(result, true);
349 /// let result = 2.0 >= 2.0;
350 /// assert_eq!(result, true);
353 #[stable(feature = "rust1", since = "1.0.0")]
354 fn ge(&self, other: &Rhs) -> bool {
355 match self.partial_cmp(other) {
356 Some(Greater) | Some(Equal) => true,
362 /// Compare and return the minimum of two values.
369 /// assert_eq!(1, cmp::min(1, 2));
370 /// assert_eq!(2, cmp::min(2, 2));
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn min<T: Ord>(v1: T, v2: T) -> T {
375 if v1 < v2 { v1 } else { v2 }
378 /// Compare and return the maximum of two values.
385 /// assert_eq!(2, cmp::max(1, 2));
386 /// assert_eq!(2, cmp::max(2, 2));
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn max<T: Ord>(v1: T, v2: T) -> T {
391 if v1 > v2 { v1 } else { v2 }
394 /// Compare and return the minimum of two values if there is one.
396 /// Returns the first argument if the comparison determines them to be equal.
403 /// assert_eq!(Some(1), cmp::partial_min(1, 2));
404 /// assert_eq!(Some(2), cmp::partial_min(2, 2));
407 /// When comparison is impossible:
412 /// let result = cmp::partial_min(std::f64::NAN, 1.0);
413 /// assert_eq!(result, None);
416 #[unstable(feature = "core")]
417 pub fn partial_min<T: PartialOrd>(v1: T, v2: T) -> Option<T> {
418 match v1.partial_cmp(&v2) {
419 Some(Less) | Some(Equal) => Some(v1),
420 Some(Greater) => Some(v2),
425 /// Compare and return the maximum of two values if there is one.
427 /// Returns the first argument if the comparison determines them to be equal.
434 /// assert_eq!(Some(2), cmp::partial_max(1, 2));
435 /// assert_eq!(Some(2), cmp::partial_max(2, 2));
438 /// When comparison is impossible:
443 /// let result = cmp::partial_max(std::f64::NAN, 1.0);
444 /// assert_eq!(result, None);
447 #[unstable(feature = "core")]
448 pub fn partial_max<T: PartialOrd>(v1: T, v2: T) -> Option<T> {
449 match v1.partial_cmp(&v2) {
450 Some(Less) => Some(v2),
451 Some(Equal) | Some(Greater) => Some(v1),
456 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
458 use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering};
459 use cmp::Ordering::{Less, Greater, Equal};
462 use option::Option::{Some, None};
464 macro_rules! partial_eq_impl {
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl PartialEq for $t {
469 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
471 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl PartialEq for () {
479 fn eq(&self, _other: &()) -> bool { true }
481 fn ne(&self, _other: &()) -> bool { false }
485 bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64
488 macro_rules! eq_impl {
490 #[stable(feature = "rust1", since = "1.0.0")]
495 eq_impl! { () bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
497 macro_rules! partial_ord_impl {
499 #[stable(feature = "rust1", since = "1.0.0")]
500 impl PartialOrd for $t {
502 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
503 match (self <= other, self >= other) {
504 (false, false) => None,
505 (false, true) => Some(Greater),
506 (true, false) => Some(Less),
507 (true, true) => Some(Equal),
511 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
513 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
515 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
517 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
522 #[stable(feature = "rust1", since = "1.0.0")]
523 impl PartialOrd for () {
525 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl PartialOrd for bool {
533 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
534 (*self as u8).partial_cmp(&(*other as u8))
538 partial_ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
540 macro_rules! ord_impl {
542 #[stable(feature = "rust1", since = "1.0.0")]
545 fn cmp(&self, other: &$t) -> Ordering {
546 if *self < *other { Less }
547 else if *self > *other { Greater }
554 #[stable(feature = "rust1", since = "1.0.0")]
557 fn cmp(&self, _other: &()) -> Ordering { Equal }
560 #[stable(feature = "rust1", since = "1.0.0")]
563 fn cmp(&self, other: &bool) -> Ordering {
564 (*self as u8).cmp(&(*other as u8))
568 ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a A where A: PartialEq<B> {
575 fn eq(&self, other: & &'b B) -> bool { PartialEq::eq(*self, *other) }
577 fn ne(&self, other: & &'b B) -> bool { PartialEq::ne(*self, *other) }
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b B> for &'a A where A: PartialOrd<B> {
582 fn partial_cmp(&self, other: &&'b B) -> Option<Ordering> {
583 PartialOrd::partial_cmp(*self, *other)
586 fn lt(&self, other: & &'b B) -> bool { PartialOrd::lt(*self, *other) }
588 fn le(&self, other: & &'b B) -> bool { PartialOrd::le(*self, *other) }
590 fn ge(&self, other: & &'b B) -> bool { PartialOrd::ge(*self, *other) }
592 fn gt(&self, other: & &'b B) -> bool { PartialOrd::gt(*self, *other) }
594 #[stable(feature = "rust1", since = "1.0.0")]
595 impl<'a, A: ?Sized> Ord for &'a A where A: Ord {
597 fn cmp(&self, other: & &'a A) -> Ordering { Ord::cmp(*self, *other) }
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl<'a, A: ?Sized> Eq for &'a A where A: Eq {}
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a mut A where A: PartialEq<B> {
607 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
609 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
611 #[stable(feature = "rust1", since = "1.0.0")]
612 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b mut B> for &'a mut A where A: PartialOrd<B> {
614 fn partial_cmp(&self, other: &&'b mut B) -> Option<Ordering> {
615 PartialOrd::partial_cmp(*self, *other)
618 fn lt(&self, other: &&'b mut B) -> bool { PartialOrd::lt(*self, *other) }
620 fn le(&self, other: &&'b mut B) -> bool { PartialOrd::le(*self, *other) }
622 fn ge(&self, other: &&'b mut B) -> bool { PartialOrd::ge(*self, *other) }
624 fn gt(&self, other: &&'b mut B) -> bool { PartialOrd::gt(*self, *other) }
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl<'a, A: ?Sized> Ord for &'a mut A where A: Ord {
629 fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<'a, A: ?Sized> Eq for &'a mut A where A: Eq {}
634 #[stable(feature = "rust1", since = "1.0.0")]
635 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a A where A: PartialEq<B> {
637 fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
639 fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a mut A where A: PartialEq<B> {
645 fn eq(&self, other: &&'b B) -> bool { PartialEq::eq(*self, *other) }
647 fn ne(&self, other: &&'b B) -> bool { PartialEq::ne(*self, *other) }