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