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