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