]> git.lizzy.rs Git - rust.git/blob - src/libcore/cmp.rs
Rollup merge of #44296 - zmanian:patch-1, r=steveklabnik
[rust.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 //! [`PartialOrd`]: trait.PartialOrd.html
19 //! [`PartialEq`]: trait.PartialEq.html
20 //!
21 //! # Examples
22 //!
23 //! ```
24 //! let x: u32 = 0;
25 //! let y: u32 = 1;
26 //!
27 //! // these two lines are equivalent
28 //! assert_eq!(x < y, true);
29 //! assert_eq!(x.lt(&y), true);
30 //!
31 //! // these two lines are also equivalent
32 //! assert_eq!(x == y, false);
33 //! assert_eq!(x.eq(&y), false);
34 //! ```
35
36 #![stable(feature = "rust1", since = "1.0.0")]
37
38 use self::Ordering::*;
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 /// ## Derivable
57 ///
58 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
59 /// instances are equal if all fields are equal, and not equal if any fields
60 /// are not equal. When `derive`d on enums, each variant is equal to itself
61 /// and not equal to the other variants.
62 ///
63 /// ## How can I implement `PartialEq`?
64 ///
65 /// PartialEq only requires the `eq` method to be implemented; `ne` is defined
66 /// in terms of it by default. Any manual implementation of `ne` *must* respect
67 /// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
68 /// only if `a != b`.
69 ///
70 /// Implementations of `PartialEq`, `PartialOrd`, and `Ord` *must* agree with
71 /// each other. It's easy to accidentally make them disagree by deriving some
72 /// of the traits and manually implementing others.
73 ///
74 /// An example implementation for a domain in which two books are considered
75 /// the same book if their ISBN matches, even if the formats differ:
76 ///
77 /// ```
78 /// enum BookFormat { Paperback, Hardback, Ebook }
79 /// struct Book {
80 ///     isbn: i32,
81 ///     format: BookFormat,
82 /// }
83 ///
84 /// impl PartialEq for Book {
85 ///     fn eq(&self, other: &Book) -> bool {
86 ///         self.isbn == other.isbn
87 ///     }
88 /// }
89 ///
90 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
91 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
92 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
93 ///
94 /// assert!(b1 == b2);
95 /// assert!(b1 != b3);
96 /// ```
97 ///
98 /// # Examples
99 ///
100 /// ```
101 /// let x: u32 = 0;
102 /// let y: u32 = 1;
103 ///
104 /// assert_eq!(x == y, false);
105 /// assert_eq!(x.eq(&y), false);
106 /// ```
107 #[lang = "eq"]
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[rustc_on_unimplemented = "can't compare `{Self}` with `{Rhs}`"]
110 pub trait PartialEq<Rhs: ?Sized = Self> {
111     /// This method tests for `self` and `other` values to be equal, and is used
112     /// by `==`.
113     #[must_use]
114     #[stable(feature = "rust1", since = "1.0.0")]
115     fn eq(&self, other: &Rhs) -> bool;
116
117     /// This method tests for `!=`.
118     #[inline]
119     #[must_use]
120     #[stable(feature = "rust1", since = "1.0.0")]
121     fn ne(&self, other: &Rhs) -> bool { !self.eq(other) }
122 }
123
124 /// Trait for equality comparisons which are [equivalence relations](
125 /// https://en.wikipedia.org/wiki/Equivalence_relation).
126 ///
127 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
128 /// be (for all `a`, `b` and `c`):
129 ///
130 /// - reflexive: `a == a`;
131 /// - symmetric: `a == b` implies `b == a`; and
132 /// - transitive: `a == b` and `b == c` implies `a == c`.
133 ///
134 /// This property cannot be checked by the compiler, and therefore `Eq` implies
135 /// `PartialEq`, and has no extra methods.
136 ///
137 /// ## Derivable
138 ///
139 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
140 /// no extra methods, it is only informing the compiler that this is an
141 /// equivalence relation rather than a partial equivalence relation. Note that
142 /// the `derive` strategy requires all fields are `Eq`, which isn't
143 /// always desired.
144 ///
145 /// ## How can I implement `Eq`?
146 ///
147 /// If you cannot use the `derive` strategy, specify that your type implements
148 /// `Eq`, which has no methods:
149 ///
150 /// ```
151 /// enum BookFormat { Paperback, Hardback, Ebook }
152 /// struct Book {
153 ///     isbn: i32,
154 ///     format: BookFormat,
155 /// }
156 /// impl PartialEq for Book {
157 ///     fn eq(&self, other: &Book) -> bool {
158 ///         self.isbn == other.isbn
159 ///     }
160 /// }
161 /// impl Eq for Book {}
162 /// ```
163 #[stable(feature = "rust1", since = "1.0.0")]
164 pub trait Eq: PartialEq<Self> {
165     // FIXME #13101: this method is used solely by #[deriving] to
166     // assert that every component of a type implements #[deriving]
167     // itself, the current deriving infrastructure means doing this
168     // assertion without using a method on this trait is nearly
169     // impossible.
170     //
171     // This should never be implemented by hand.
172     #[doc(hidden)]
173     #[inline]
174     #[stable(feature = "rust1", since = "1.0.0")]
175     fn assert_receiver_is_total_eq(&self) {}
176 }
177
178 // FIXME: this struct is used solely by #[derive] to
179 // assert that every component of a type implements Eq.
180 //
181 // This struct should never appear in user code.
182 #[doc(hidden)]
183 #[allow(missing_debug_implementations)]
184 #[unstable(feature = "derive_eq",
185            reason = "deriving hack, should not be public",
186            issue = "0")]
187 pub struct AssertParamIsEq<T: Eq + ?Sized> { _field: ::marker::PhantomData<T> }
188
189 /// An `Ordering` is the result of a comparison between two values.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use std::cmp::Ordering;
195 ///
196 /// let result = 1.cmp(&2);
197 /// assert_eq!(Ordering::Less, result);
198 ///
199 /// let result = 1.cmp(&1);
200 /// assert_eq!(Ordering::Equal, result);
201 ///
202 /// let result = 2.cmp(&1);
203 /// assert_eq!(Ordering::Greater, result);
204 /// ```
205 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub enum Ordering {
208     /// An ordering where a compared value is less [than another].
209     #[stable(feature = "rust1", since = "1.0.0")]
210     Less = -1,
211     /// An ordering where a compared value is equal [to another].
212     #[stable(feature = "rust1", since = "1.0.0")]
213     Equal = 0,
214     /// An ordering where a compared value is greater [than another].
215     #[stable(feature = "rust1", since = "1.0.0")]
216     Greater = 1,
217 }
218
219 impl Ordering {
220     /// Reverses the `Ordering`.
221     ///
222     /// * `Less` becomes `Greater`.
223     /// * `Greater` becomes `Less`.
224     /// * `Equal` becomes `Equal`.
225     ///
226     /// # Examples
227     ///
228     /// Basic behavior:
229     ///
230     /// ```
231     /// use std::cmp::Ordering;
232     ///
233     /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
234     /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
235     /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
236     /// ```
237     ///
238     /// This method can be used to reverse a comparison:
239     ///
240     /// ```
241     /// let mut data: &mut [_] = &mut [2, 10, 5, 8];
242     ///
243     /// // sort the array from largest to smallest.
244     /// data.sort_by(|a, b| a.cmp(b).reverse());
245     ///
246     /// let b: &mut [_] = &mut [10, 8, 5, 2];
247     /// assert!(data == b);
248     /// ```
249     #[inline]
250     #[stable(feature = "rust1", since = "1.0.0")]
251     pub fn reverse(self) -> Ordering {
252         match self {
253             Less => Greater,
254             Equal => Equal,
255             Greater => Less,
256         }
257     }
258
259     /// Chains two orderings.
260     ///
261     /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
262     /// # Examples
263     ///
264     /// ```
265     /// use std::cmp::Ordering;
266     ///
267     /// let result = Ordering::Equal.then(Ordering::Less);
268     /// assert_eq!(result, Ordering::Less);
269     ///
270     /// let result = Ordering::Less.then(Ordering::Equal);
271     /// assert_eq!(result, Ordering::Less);
272     ///
273     /// let result = Ordering::Less.then(Ordering::Greater);
274     /// assert_eq!(result, Ordering::Less);
275     ///
276     /// let result = Ordering::Equal.then(Ordering::Equal);
277     /// assert_eq!(result, Ordering::Equal);
278     ///
279     /// let x: (i64, i64, i64) = (1, 2, 7);
280     /// let y: (i64, i64, i64) = (1, 5, 3);
281     /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
282     ///
283     /// assert_eq!(result, Ordering::Less);
284     /// ```
285     #[inline]
286     #[stable(feature = "ordering_chaining", since = "1.17.0")]
287     pub fn then(self, other: Ordering) -> Ordering {
288         match self {
289             Equal => other,
290             _ => self,
291         }
292     }
293
294     /// Chains the ordering with the given function.
295     ///
296     /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
297     /// the result.
298     ///
299     /// # Examples
300     ///
301     /// ```
302     /// use std::cmp::Ordering;
303     ///
304     /// let result = Ordering::Equal.then_with(|| Ordering::Less);
305     /// assert_eq!(result, Ordering::Less);
306     ///
307     /// let result = Ordering::Less.then_with(|| Ordering::Equal);
308     /// assert_eq!(result, Ordering::Less);
309     ///
310     /// let result = Ordering::Less.then_with(|| Ordering::Greater);
311     /// assert_eq!(result, Ordering::Less);
312     ///
313     /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
314     /// assert_eq!(result, Ordering::Equal);
315     ///
316     /// let x: (i64, i64, i64) = (1, 2, 7);
317     /// let y: (i64, i64, i64)  = (1, 5, 3);
318     /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
319     ///
320     /// assert_eq!(result, Ordering::Less);
321     /// ```
322     #[inline]
323     #[stable(feature = "ordering_chaining", since = "1.17.0")]
324     pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
325         match self {
326             Equal => f(),
327             _ => self,
328         }
329     }
330 }
331
332 /// A helper struct for reverse ordering.
333 ///
334 /// This struct is a helper to be used with functions like `Vec::sort_by_key` and
335 /// can be used to reverse order a part of a key.
336 ///
337 /// Example usage:
338 ///
339 /// ```
340 /// use std::cmp::Reverse;
341 ///
342 /// let mut v = vec![1, 2, 3, 4, 5, 6];
343 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
344 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
345 /// ```
346 #[derive(PartialEq, Eq, Debug)]
347 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
348 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
349
350 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
351 impl<T: PartialOrd> PartialOrd for Reverse<T> {
352     #[inline]
353     fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
354         other.0.partial_cmp(&self.0)
355     }
356
357     #[inline]
358     fn lt(&self, other: &Self) -> bool { other.0 < self.0 }
359     #[inline]
360     fn le(&self, other: &Self) -> bool { other.0 <= self.0 }
361     #[inline]
362     fn ge(&self, other: &Self) -> bool { other.0 >= self.0 }
363     #[inline]
364     fn gt(&self, other: &Self) -> bool { other.0 > self.0 }
365 }
366
367 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
368 impl<T: Ord> Ord for Reverse<T> {
369     #[inline]
370     fn cmp(&self, other: &Reverse<T>) -> Ordering {
371         other.0.cmp(&self.0)
372     }
373 }
374
375 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
376 ///
377 /// An order is a total order if it is (for all `a`, `b` and `c`):
378 ///
379 /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
380 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
381 ///
382 /// ## Derivable
383 ///
384 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
385 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
386 /// When `derive`d on enums, variants are ordered by their top-to-bottom declaration order.
387 ///
388 /// ## How can I implement `Ord`?
389 ///
390 /// `Ord` requires that the type also be `PartialOrd` and `Eq` (which requires `PartialEq`).
391 ///
392 /// Then you must define an implementation for `cmp()`. You may find it useful to use
393 /// `cmp()` on your type's fields.
394 ///
395 /// Implementations of `PartialEq`, `PartialOrd`, and `Ord` *must* agree with each other. It's
396 /// easy to accidentally make them disagree by deriving some of the traits and manually
397 /// implementing others.
398 ///
399 /// Here's an example where you want to sort people by height only, disregarding `id`
400 /// and `name`:
401 ///
402 /// ```
403 /// use std::cmp::Ordering;
404 ///
405 /// #[derive(Eq)]
406 /// struct Person {
407 ///     id: u32,
408 ///     name: String,
409 ///     height: u32,
410 /// }
411 ///
412 /// impl Ord for Person {
413 ///     fn cmp(&self, other: &Person) -> Ordering {
414 ///         self.height.cmp(&other.height)
415 ///     }
416 /// }
417 ///
418 /// impl PartialOrd for Person {
419 ///     fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
420 ///         Some(self.cmp(other))
421 ///     }
422 /// }
423 ///
424 /// impl PartialEq for Person {
425 ///     fn eq(&self, other: &Person) -> bool {
426 ///         self.height == other.height
427 ///     }
428 /// }
429 /// ```
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub trait Ord: Eq + PartialOrd<Self> {
432     /// This method returns an `Ordering` between `self` and `other`.
433     ///
434     /// By convention, `self.cmp(&other)` returns the ordering matching the expression
435     /// `self <operator> other` if true.
436     ///
437     /// # Examples
438     ///
439     /// ```
440     /// use std::cmp::Ordering;
441     ///
442     /// assert_eq!(5.cmp(&10), Ordering::Less);
443     /// assert_eq!(10.cmp(&5), Ordering::Greater);
444     /// assert_eq!(5.cmp(&5), Ordering::Equal);
445     /// ```
446     #[stable(feature = "rust1", since = "1.0.0")]
447     fn cmp(&self, other: &Self) -> Ordering;
448
449     /// Compares and returns the maximum of two values.
450     ///
451     /// Returns the second argument if the comparison determines them to be equal.
452     ///
453     /// # Examples
454     ///
455     /// ```
456     /// #![feature(ord_max_min)]
457     ///
458     /// assert_eq!(2, 1.max(2));
459     /// assert_eq!(2, 2.max(2));
460     /// ```
461     #[unstable(feature = "ord_max_min", issue = "25663")]
462     fn max(self, other: Self) -> Self
463     where Self: Sized {
464         if other >= self { other } else { self }
465     }
466
467     /// Compares and returns the minimum of two values.
468     ///
469     /// Returns the first argument if the comparison determines them to be equal.
470     ///
471     /// # Examples
472     ///
473     /// ```
474     /// #![feature(ord_max_min)]
475     ///
476     /// assert_eq!(1, 1.min(2));
477     /// assert_eq!(2, 2.min(2));
478     /// ```
479     #[unstable(feature = "ord_max_min", issue = "25663")]
480     fn min(self, other: Self) -> Self
481     where Self: Sized {
482         if self <= other { self } else { other }
483     }
484
485     /// Returns max if self is greater than max, and min if self is less than min.
486     /// Otherwise this will return self.
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// #![feature(clamp)]
492     ///
493     /// assert!((-3).clamp(-2, 1) == -2);
494     /// assert!(0.clamp(-2, 1) == 0);
495     /// assert!(2.clamp(-2, 1) == 1);
496     /// ```
497     ///
498     /// # Panics
499     /// Panics if min > max.
500     #[unstable(feature = "clamp", issue = "44095")]
501     fn clamp(self, min: Self, max: Self) -> Self
502     where Self: Sized {
503         assert!(min <= max);
504         if self < min { min }
505         else if self > max { max }
506         else { self }
507     }
508 }
509
510 #[stable(feature = "rust1", since = "1.0.0")]
511 impl Eq for Ordering {}
512
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl Ord for Ordering {
515     #[inline]
516     fn cmp(&self, other: &Ordering) -> Ordering {
517         (*self as i32).cmp(&(*other as i32))
518     }
519 }
520
521 #[stable(feature = "rust1", since = "1.0.0")]
522 impl PartialOrd for Ordering {
523     #[inline]
524     fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
525         (*self as i32).partial_cmp(&(*other as i32))
526     }
527 }
528
529 /// Trait for values that can be compared for a sort-order.
530 ///
531 /// The comparison must satisfy, for all `a`, `b` and `c`:
532 ///
533 /// - antisymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
534 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
535 ///
536 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
537 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
538 /// PartialOrd<V>`.
539 ///
540 /// ## Derivable
541 ///
542 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
543 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
544 /// When `derive`d on enums, variants are ordered by their top-to-bottom declaration order.
545 ///
546 /// ## How can I implement `PartialOrd`?
547 ///
548 /// `PartialOrd` only requires implementation of the `partial_cmp` method, with the others
549 /// generated from default implementations.
550 ///
551 /// However it remains possible to implement the others separately for types which do not have a
552 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
553 /// false` (cf. IEEE 754-2008 section 5.11).
554 ///
555 /// `PartialOrd` requires your type to be `PartialEq`.
556 ///
557 /// Implementations of `PartialEq`, `PartialOrd`, and `Ord` *must* agree with each other. It's
558 /// easy to accidentally make them disagree by deriving some of the traits and manually
559 /// implementing others.
560 ///
561 /// If your type is `Ord`, you can implement `partial_cmp()` by using `cmp()`:
562 ///
563 /// ```
564 /// use std::cmp::Ordering;
565 ///
566 /// #[derive(Eq)]
567 /// struct Person {
568 ///     id: u32,
569 ///     name: String,
570 ///     height: u32,
571 /// }
572 ///
573 /// impl PartialOrd for Person {
574 ///     fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
575 ///         Some(self.cmp(other))
576 ///     }
577 /// }
578 ///
579 /// impl Ord for Person {
580 ///     fn cmp(&self, other: &Person) -> Ordering {
581 ///         self.height.cmp(&other.height)
582 ///     }
583 /// }
584 ///
585 /// impl PartialEq for Person {
586 ///     fn eq(&self, other: &Person) -> bool {
587 ///         self.height == other.height
588 ///     }
589 /// }
590 /// ```
591 ///
592 /// You may also find it useful to use `partial_cmp()` on your type's fields. Here
593 /// is an example of `Person` types who have a floating-point `height` field that
594 /// is the only field to be used for sorting:
595 ///
596 /// ```
597 /// use std::cmp::Ordering;
598 ///
599 /// struct Person {
600 ///     id: u32,
601 ///     name: String,
602 ///     height: f64,
603 /// }
604 ///
605 /// impl PartialOrd for Person {
606 ///     fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
607 ///         self.height.partial_cmp(&other.height)
608 ///     }
609 /// }
610 ///
611 /// impl PartialEq for Person {
612 ///     fn eq(&self, other: &Person) -> bool {
613 ///         self.height == other.height
614 ///     }
615 /// }
616 /// ```
617 ///
618 /// # Examples
619 ///
620 /// ```
621 /// let x : u32 = 0;
622 /// let y : u32 = 1;
623 ///
624 /// assert_eq!(x < y, true);
625 /// assert_eq!(x.lt(&y), true);
626 /// ```
627 #[lang = "ord"]
628 #[stable(feature = "rust1", since = "1.0.0")]
629 #[rustc_on_unimplemented = "can't compare `{Self}` with `{Rhs}`"]
630 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
631     /// This method returns an ordering between `self` and `other` values if one exists.
632     ///
633     /// # Examples
634     ///
635     /// ```
636     /// use std::cmp::Ordering;
637     ///
638     /// let result = 1.0.partial_cmp(&2.0);
639     /// assert_eq!(result, Some(Ordering::Less));
640     ///
641     /// let result = 1.0.partial_cmp(&1.0);
642     /// assert_eq!(result, Some(Ordering::Equal));
643     ///
644     /// let result = 2.0.partial_cmp(&1.0);
645     /// assert_eq!(result, Some(Ordering::Greater));
646     /// ```
647     ///
648     /// When comparison is impossible:
649     ///
650     /// ```
651     /// let result = std::f64::NAN.partial_cmp(&1.0);
652     /// assert_eq!(result, None);
653     /// ```
654     #[must_use]
655     #[stable(feature = "rust1", since = "1.0.0")]
656     fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
657
658     /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
659     ///
660     /// # Examples
661     ///
662     /// ```
663     /// let result = 1.0 < 2.0;
664     /// assert_eq!(result, true);
665     ///
666     /// let result = 2.0 < 1.0;
667     /// assert_eq!(result, false);
668     /// ```
669     #[inline]
670     #[must_use]
671     #[stable(feature = "rust1", since = "1.0.0")]
672     fn lt(&self, other: &Rhs) -> bool {
673         match self.partial_cmp(other) {
674             Some(Less) => true,
675             _ => false,
676         }
677     }
678
679     /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
680     /// operator.
681     ///
682     /// # Examples
683     ///
684     /// ```
685     /// let result = 1.0 <= 2.0;
686     /// assert_eq!(result, true);
687     ///
688     /// let result = 2.0 <= 2.0;
689     /// assert_eq!(result, true);
690     /// ```
691     #[inline]
692     #[must_use]
693     #[stable(feature = "rust1", since = "1.0.0")]
694     fn le(&self, other: &Rhs) -> bool {
695         match self.partial_cmp(other) {
696             Some(Less) | Some(Equal) => true,
697             _ => false,
698         }
699     }
700
701     /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
702     ///
703     /// # Examples
704     ///
705     /// ```
706     /// let result = 1.0 > 2.0;
707     /// assert_eq!(result, false);
708     ///
709     /// let result = 2.0 > 2.0;
710     /// assert_eq!(result, false);
711     /// ```
712     #[inline]
713     #[must_use]
714     #[stable(feature = "rust1", since = "1.0.0")]
715     fn gt(&self, other: &Rhs) -> bool {
716         match self.partial_cmp(other) {
717             Some(Greater) => true,
718             _ => false,
719         }
720     }
721
722     /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
723     /// operator.
724     ///
725     /// # Examples
726     ///
727     /// ```
728     /// let result = 2.0 >= 1.0;
729     /// assert_eq!(result, true);
730     ///
731     /// let result = 2.0 >= 2.0;
732     /// assert_eq!(result, true);
733     /// ```
734     #[inline]
735     #[must_use]
736     #[stable(feature = "rust1", since = "1.0.0")]
737     fn ge(&self, other: &Rhs) -> bool {
738         match self.partial_cmp(other) {
739             Some(Greater) | Some(Equal) => true,
740             _ => false,
741         }
742     }
743 }
744
745 /// Compares and returns the minimum of two values.
746 ///
747 /// Returns the first argument if the comparison determines them to be equal.
748 ///
749 /// Internally uses an alias to `Ord::min`.
750 ///
751 /// # Examples
752 ///
753 /// ```
754 /// use std::cmp;
755 ///
756 /// assert_eq!(1, cmp::min(1, 2));
757 /// assert_eq!(2, cmp::min(2, 2));
758 /// ```
759 #[inline]
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn min<T: Ord>(v1: T, v2: T) -> T {
762     v1.min(v2)
763 }
764
765 /// Compares and returns the maximum of two values.
766 ///
767 /// Returns the second argument if the comparison determines them to be equal.
768 ///
769 /// Internally uses an alias to `Ord::max`.
770 ///
771 /// # Examples
772 ///
773 /// ```
774 /// use std::cmp;
775 ///
776 /// assert_eq!(2, cmp::max(1, 2));
777 /// assert_eq!(2, cmp::max(2, 2));
778 /// ```
779 #[inline]
780 #[stable(feature = "rust1", since = "1.0.0")]
781 pub fn max<T: Ord>(v1: T, v2: T) -> T {
782     v1.max(v2)
783 }
784
785 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
786 mod impls {
787     use cmp::Ordering::{self, Less, Greater, Equal};
788
789     macro_rules! partial_eq_impl {
790         ($($t:ty)*) => ($(
791             #[stable(feature = "rust1", since = "1.0.0")]
792             impl PartialEq for $t {
793                 #[inline]
794                 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
795                 #[inline]
796                 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
797             }
798         )*)
799     }
800
801     #[stable(feature = "rust1", since = "1.0.0")]
802     impl PartialEq for () {
803         #[inline]
804         fn eq(&self, _other: &()) -> bool { true }
805         #[inline]
806         fn ne(&self, _other: &()) -> bool { false }
807     }
808
809     partial_eq_impl! {
810         bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
811     }
812
813     macro_rules! eq_impl {
814         ($($t:ty)*) => ($(
815             #[stable(feature = "rust1", since = "1.0.0")]
816             impl Eq for $t {}
817         )*)
818     }
819
820     eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
821
822     macro_rules! partial_ord_impl {
823         ($($t:ty)*) => ($(
824             #[stable(feature = "rust1", since = "1.0.0")]
825             impl PartialOrd for $t {
826                 #[inline]
827                 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
828                     match (self <= other, self >= other) {
829                         (false, false) => None,
830                         (false, true) => Some(Greater),
831                         (true, false) => Some(Less),
832                         (true, true) => Some(Equal),
833                     }
834                 }
835                 #[inline]
836                 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
837                 #[inline]
838                 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
839                 #[inline]
840                 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
841                 #[inline]
842                 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
843             }
844         )*)
845     }
846
847     #[stable(feature = "rust1", since = "1.0.0")]
848     impl PartialOrd for () {
849         #[inline]
850         fn partial_cmp(&self, _: &()) -> Option<Ordering> {
851             Some(Equal)
852         }
853     }
854
855     #[stable(feature = "rust1", since = "1.0.0")]
856     impl PartialOrd for bool {
857         #[inline]
858         fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
859             (*self as u8).partial_cmp(&(*other as u8))
860         }
861     }
862
863     partial_ord_impl! { f32 f64 }
864
865     macro_rules! ord_impl {
866         ($($t:ty)*) => ($(
867             #[stable(feature = "rust1", since = "1.0.0")]
868             impl PartialOrd for $t {
869                 #[inline]
870                 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
871                     Some(self.cmp(other))
872                 }
873                 #[inline]
874                 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
875                 #[inline]
876                 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
877                 #[inline]
878                 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
879                 #[inline]
880                 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
881             }
882
883             #[stable(feature = "rust1", since = "1.0.0")]
884             impl Ord for $t {
885                 #[inline]
886                 fn cmp(&self, other: &$t) -> Ordering {
887                     if *self == *other { Equal }
888                     else if *self < *other { Less }
889                     else { Greater }
890                 }
891             }
892         )*)
893     }
894
895     #[stable(feature = "rust1", since = "1.0.0")]
896     impl Ord for () {
897         #[inline]
898         fn cmp(&self, _other: &()) -> Ordering { Equal }
899     }
900
901     #[stable(feature = "rust1", since = "1.0.0")]
902     impl Ord for bool {
903         #[inline]
904         fn cmp(&self, other: &bool) -> Ordering {
905             (*self as u8).cmp(&(*other as u8))
906         }
907     }
908
909     ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
910
911     #[unstable(feature = "never_type_impls", issue = "35121")]
912     impl PartialEq for ! {
913         fn eq(&self, _: &!) -> bool {
914             *self
915         }
916     }
917
918     #[unstable(feature = "never_type_impls", issue = "35121")]
919     impl Eq for ! {}
920
921     #[unstable(feature = "never_type_impls", issue = "35121")]
922     impl PartialOrd for ! {
923         fn partial_cmp(&self, _: &!) -> Option<Ordering> {
924             *self
925         }
926     }
927
928     #[unstable(feature = "never_type_impls", issue = "35121")]
929     impl Ord for ! {
930         fn cmp(&self, _: &!) -> Ordering {
931             *self
932         }
933     }
934
935     // & pointers
936
937     #[stable(feature = "rust1", since = "1.0.0")]
938     impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a A where A: PartialEq<B> {
939         #[inline]
940         fn eq(&self, other: & &'b B) -> bool { PartialEq::eq(*self, *other) }
941         #[inline]
942         fn ne(&self, other: & &'b B) -> bool { PartialEq::ne(*self, *other) }
943     }
944     #[stable(feature = "rust1", since = "1.0.0")]
945     impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b B> for &'a A where A: PartialOrd<B> {
946         #[inline]
947         fn partial_cmp(&self, other: &&'b B) -> Option<Ordering> {
948             PartialOrd::partial_cmp(*self, *other)
949         }
950         #[inline]
951         fn lt(&self, other: & &'b B) -> bool { PartialOrd::lt(*self, *other) }
952         #[inline]
953         fn le(&self, other: & &'b B) -> bool { PartialOrd::le(*self, *other) }
954         #[inline]
955         fn ge(&self, other: & &'b B) -> bool { PartialOrd::ge(*self, *other) }
956         #[inline]
957         fn gt(&self, other: & &'b B) -> bool { PartialOrd::gt(*self, *other) }
958     }
959     #[stable(feature = "rust1", since = "1.0.0")]
960     impl<'a, A: ?Sized> Ord for &'a A where A: Ord {
961         #[inline]
962         fn cmp(&self, other: & &'a A) -> Ordering { Ord::cmp(*self, *other) }
963     }
964     #[stable(feature = "rust1", since = "1.0.0")]
965     impl<'a, A: ?Sized> Eq for &'a A where A: Eq {}
966
967     // &mut pointers
968
969     #[stable(feature = "rust1", since = "1.0.0")]
970     impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a mut A where A: PartialEq<B> {
971         #[inline]
972         fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
973         #[inline]
974         fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
975     }
976     #[stable(feature = "rust1", since = "1.0.0")]
977     impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<&'b mut B> for &'a mut A where A: PartialOrd<B> {
978         #[inline]
979         fn partial_cmp(&self, other: &&'b mut B) -> Option<Ordering> {
980             PartialOrd::partial_cmp(*self, *other)
981         }
982         #[inline]
983         fn lt(&self, other: &&'b mut B) -> bool { PartialOrd::lt(*self, *other) }
984         #[inline]
985         fn le(&self, other: &&'b mut B) -> bool { PartialOrd::le(*self, *other) }
986         #[inline]
987         fn ge(&self, other: &&'b mut B) -> bool { PartialOrd::ge(*self, *other) }
988         #[inline]
989         fn gt(&self, other: &&'b mut B) -> bool { PartialOrd::gt(*self, *other) }
990     }
991     #[stable(feature = "rust1", since = "1.0.0")]
992     impl<'a, A: ?Sized> Ord for &'a mut A where A: Ord {
993         #[inline]
994         fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
995     }
996     #[stable(feature = "rust1", since = "1.0.0")]
997     impl<'a, A: ?Sized> Eq for &'a mut A where A: Eq {}
998
999     #[stable(feature = "rust1", since = "1.0.0")]
1000     impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b mut B> for &'a A where A: PartialEq<B> {
1001         #[inline]
1002         fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) }
1003         #[inline]
1004         fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) }
1005     }
1006
1007     #[stable(feature = "rust1", since = "1.0.0")]
1008     impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<&'b B> for &'a mut A where A: PartialEq<B> {
1009         #[inline]
1010         fn eq(&self, other: &&'b B) -> bool { PartialEq::eq(*self, *other) }
1011         #[inline]
1012         fn ne(&self, other: &&'b B) -> bool { PartialEq::ne(*self, *other) }
1013     }
1014 }