]> git.lizzy.rs Git - rust.git/blob - library/core/src/cmp.rs
Clear up discriminants with more examples
[rust.git] / library / core / src / 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`] is an enum returned by the main functions of [`Ord`] and
13 //!   [`PartialOrd`], and describes an ordering.
14 //! * [`Reverse`] is a struct that allows you to easily reverse an ordering.
15 //! * [`max`] and [`min`] are functions that build off of [`Ord`] and allow you
16 //!   to find the maximum or minimum of two values.
17 //!
18 //! For more details, see the respective documentation of each item in the list.
19 //!
20 //! [`max`]: Ord::max
21 //! [`min`]: Ord::min
22
23 #![stable(feature = "rust1", since = "1.0.0")]
24
25 use self::Ordering::*;
26
27 /// Trait for equality comparisons which are [partial equivalence
28 /// relations](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
29 ///
30 /// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
31 /// We use the easier-to-read infix notation in the remainder of this documentation.
32 ///
33 /// This trait allows for partial equality, for types that do not have a full
34 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
35 /// so floating point types implement `PartialEq` but not [`trait@Eq`].
36 ///
37 /// Implementations must ensure that `eq` and `ne` are consistent with each other:
38 ///
39 /// - `a != b` if and only if `!(a == b)`
40 ///   (ensured by the default implementation).
41 ///
42 /// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
43 /// be consistent with `PartialEq` (see the documentation of those traits for the exact
44 /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
45 /// manually implementing others.
46 ///
47 /// The equality relation `==` must satisfy the following conditions
48 /// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
49 ///
50 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
51 ///   implies `b == a`**; and
52 ///
53 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
54 ///   PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
55 ///
56 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
57 /// (transitive) impls are not forced to exist, but these requirements apply
58 /// whenever they do exist.
59 ///
60 /// ## Derivable
61 ///
62 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
63 /// instances are equal if all fields are equal, and not equal if any fields
64 /// are not equal. When `derive`d on enums, each variant is equal to itself
65 /// and not equal to the other variants.
66 ///
67 /// ## How can I implement `PartialEq`?
68 ///
69 /// An example implementation for a domain in which two books are considered
70 /// the same book if their ISBN matches, even if the formats differ:
71 ///
72 /// ```
73 /// enum BookFormat {
74 ///     Paperback,
75 ///     Hardback,
76 ///     Ebook,
77 /// }
78 ///
79 /// struct Book {
80 ///     isbn: i32,
81 ///     format: BookFormat,
82 /// }
83 ///
84 /// impl PartialEq for Book {
85 ///     fn eq(&self, other: &Self) -> 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 /// ## How can I compare two different types?
99 ///
100 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
101 /// For example, let's tweak our previous code a bit:
102 ///
103 /// ```
104 /// // The derive implements <BookFormat> == <BookFormat> comparisons
105 /// #[derive(PartialEq)]
106 /// enum BookFormat {
107 ///     Paperback,
108 ///     Hardback,
109 ///     Ebook,
110 /// }
111 ///
112 /// struct Book {
113 ///     isbn: i32,
114 ///     format: BookFormat,
115 /// }
116 ///
117 /// // Implement <Book> == <BookFormat> comparisons
118 /// impl PartialEq<BookFormat> for Book {
119 ///     fn eq(&self, other: &BookFormat) -> bool {
120 ///         self.format == *other
121 ///     }
122 /// }
123 ///
124 /// // Implement <BookFormat> == <Book> comparisons
125 /// impl PartialEq<Book> for BookFormat {
126 ///     fn eq(&self, other: &Book) -> bool {
127 ///         *self == other.format
128 ///     }
129 /// }
130 ///
131 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
132 ///
133 /// assert!(b1 == BookFormat::Paperback);
134 /// assert!(BookFormat::Ebook != b1);
135 /// ```
136 ///
137 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
138 /// we allow `BookFormat`s to be compared with `Book`s.
139 ///
140 /// A comparison like the one above, which ignores some fields of the struct,
141 /// can be dangerous. It can easily lead to an unintended violation of the
142 /// requirements for a partial equivalence relation. For example, if we kept
143 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
144 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
145 /// via the manual implementation from the first example) then the result would
146 /// violate transitivity:
147 ///
148 /// ```should_panic
149 /// #[derive(PartialEq)]
150 /// enum BookFormat {
151 ///     Paperback,
152 ///     Hardback,
153 ///     Ebook,
154 /// }
155 ///
156 /// #[derive(PartialEq)]
157 /// struct Book {
158 ///     isbn: i32,
159 ///     format: BookFormat,
160 /// }
161 ///
162 /// impl PartialEq<BookFormat> for Book {
163 ///     fn eq(&self, other: &BookFormat) -> bool {
164 ///         self.format == *other
165 ///     }
166 /// }
167 ///
168 /// impl PartialEq<Book> for BookFormat {
169 ///     fn eq(&self, other: &Book) -> bool {
170 ///         *self == other.format
171 ///     }
172 /// }
173 ///
174 /// fn main() {
175 ///     let b1 = Book { isbn: 1, format: BookFormat::Paperback };
176 ///     let b2 = Book { isbn: 2, format: BookFormat::Paperback };
177 ///
178 ///     assert!(b1 == BookFormat::Paperback);
179 ///     assert!(BookFormat::Paperback == b2);
180 ///
181 ///     // The following should hold by transitivity but doesn't.
182 ///     assert!(b1 == b2); // <-- PANICS
183 /// }
184 /// ```
185 ///
186 /// # Examples
187 ///
188 /// ```
189 /// let x: u32 = 0;
190 /// let y: u32 = 1;
191 ///
192 /// assert_eq!(x == y, false);
193 /// assert_eq!(x.eq(&y), false);
194 /// ```
195 ///
196 /// [`eq`]: PartialEq::eq
197 /// [`ne`]: PartialEq::ne
198 #[lang = "eq"]
199 #[stable(feature = "rust1", since = "1.0.0")]
200 #[doc(alias = "==")]
201 #[doc(alias = "!=")]
202 #[rustc_on_unimplemented(
203     message = "can't compare `{Self}` with `{Rhs}`",
204     label = "no implementation for `{Self} == {Rhs}`"
205 )]
206 #[rustc_diagnostic_item = "PartialEq"]
207 pub trait PartialEq<Rhs: ?Sized = Self> {
208     /// This method tests for `self` and `other` values to be equal, and is used
209     /// by `==`.
210     #[must_use]
211     #[stable(feature = "rust1", since = "1.0.0")]
212     fn eq(&self, other: &Rhs) -> bool;
213
214     /// This method tests for `!=`.
215     #[inline]
216     #[must_use]
217     #[stable(feature = "rust1", since = "1.0.0")]
218     #[default_method_body_is_const]
219     fn ne(&self, other: &Rhs) -> bool {
220         !self.eq(other)
221     }
222 }
223
224 /// Derive macro generating an impl of the trait `PartialEq`.
225 #[rustc_builtin_macro]
226 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
227 #[allow_internal_unstable(core_intrinsics, structural_match)]
228 pub macro PartialEq($item:item) {
229     /* compiler built-in */
230 }
231
232 /// Trait for equality comparisons which are [equivalence relations](
233 /// https://en.wikipedia.org/wiki/Equivalence_relation).
234 ///
235 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
236 /// be (for all `a`, `b` and `c`):
237 ///
238 /// - reflexive: `a == a`;
239 /// - symmetric: `a == b` implies `b == a`; and
240 /// - transitive: `a == b` and `b == c` implies `a == c`.
241 ///
242 /// This property cannot be checked by the compiler, and therefore `Eq` implies
243 /// [`PartialEq`], and has no extra methods.
244 ///
245 /// ## Derivable
246 ///
247 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
248 /// no extra methods, it is only informing the compiler that this is an
249 /// equivalence relation rather than a partial equivalence relation. Note that
250 /// the `derive` strategy requires all fields are `Eq`, which isn't
251 /// always desired.
252 ///
253 /// ## How can I implement `Eq`?
254 ///
255 /// If you cannot use the `derive` strategy, specify that your type implements
256 /// `Eq`, which has no methods:
257 ///
258 /// ```
259 /// enum BookFormat { Paperback, Hardback, Ebook }
260 /// struct Book {
261 ///     isbn: i32,
262 ///     format: BookFormat,
263 /// }
264 /// impl PartialEq for Book {
265 ///     fn eq(&self, other: &Self) -> bool {
266 ///         self.isbn == other.isbn
267 ///     }
268 /// }
269 /// impl Eq for Book {}
270 /// ```
271 #[doc(alias = "==")]
272 #[doc(alias = "!=")]
273 #[stable(feature = "rust1", since = "1.0.0")]
274 #[rustc_diagnostic_item = "Eq"]
275 pub trait Eq: PartialEq<Self> {
276     // this method is used solely by #[deriving] to assert
277     // that every component of a type implements #[deriving]
278     // itself, the current deriving infrastructure means doing this
279     // assertion without using a method on this trait is nearly
280     // impossible.
281     //
282     // This should never be implemented by hand.
283     #[doc(hidden)]
284     #[no_coverage] // rust-lang/rust#84605
285     #[inline]
286     #[stable(feature = "rust1", since = "1.0.0")]
287     fn assert_receiver_is_total_eq(&self) {}
288 }
289
290 /// Derive macro generating an impl of the trait `Eq`.
291 #[rustc_builtin_macro]
292 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
293 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
294 pub macro Eq($item:item) {
295     /* compiler built-in */
296 }
297
298 // FIXME: this struct is used solely by #[derive] to
299 // assert that every component of a type implements Eq.
300 //
301 // This struct should never appear in user code.
302 #[doc(hidden)]
303 #[allow(missing_debug_implementations)]
304 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
305 pub struct AssertParamIsEq<T: Eq + ?Sized> {
306     _field: crate::marker::PhantomData<T>,
307 }
308
309 /// An `Ordering` is the result of a comparison between two values.
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// use std::cmp::Ordering;
315 ///
316 /// let result = 1.cmp(&2);
317 /// assert_eq!(Ordering::Less, result);
318 ///
319 /// let result = 1.cmp(&1);
320 /// assert_eq!(Ordering::Equal, result);
321 ///
322 /// let result = 2.cmp(&1);
323 /// assert_eq!(Ordering::Greater, result);
324 /// ```
325 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
326 #[stable(feature = "rust1", since = "1.0.0")]
327 #[repr(i8)]
328 pub enum Ordering {
329     /// An ordering where a compared value is less than another.
330     #[stable(feature = "rust1", since = "1.0.0")]
331     Less = -1,
332     /// An ordering where a compared value is equal to another.
333     #[stable(feature = "rust1", since = "1.0.0")]
334     Equal = 0,
335     /// An ordering where a compared value is greater than another.
336     #[stable(feature = "rust1", since = "1.0.0")]
337     Greater = 1,
338 }
339
340 impl Ordering {
341     /// Returns `true` if the ordering is the `Equal` variant.
342     ///
343     /// # Examples
344     ///
345     /// ```
346     /// use std::cmp::Ordering;
347     ///
348     /// assert_eq!(Ordering::Less.is_eq(), false);
349     /// assert_eq!(Ordering::Equal.is_eq(), true);
350     /// assert_eq!(Ordering::Greater.is_eq(), false);
351     /// ```
352     #[inline]
353     #[must_use]
354     #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
355     #[stable(feature = "ordering_helpers", since = "1.53.0")]
356     pub const fn is_eq(self) -> bool {
357         matches!(self, Equal)
358     }
359
360     /// Returns `true` if the ordering is not the `Equal` variant.
361     ///
362     /// # Examples
363     ///
364     /// ```
365     /// use std::cmp::Ordering;
366     ///
367     /// assert_eq!(Ordering::Less.is_ne(), true);
368     /// assert_eq!(Ordering::Equal.is_ne(), false);
369     /// assert_eq!(Ordering::Greater.is_ne(), true);
370     /// ```
371     #[inline]
372     #[must_use]
373     #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
374     #[stable(feature = "ordering_helpers", since = "1.53.0")]
375     pub const fn is_ne(self) -> bool {
376         !matches!(self, Equal)
377     }
378
379     /// Returns `true` if the ordering is the `Less` variant.
380     ///
381     /// # Examples
382     ///
383     /// ```
384     /// use std::cmp::Ordering;
385     ///
386     /// assert_eq!(Ordering::Less.is_lt(), true);
387     /// assert_eq!(Ordering::Equal.is_lt(), false);
388     /// assert_eq!(Ordering::Greater.is_lt(), false);
389     /// ```
390     #[inline]
391     #[must_use]
392     #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
393     #[stable(feature = "ordering_helpers", since = "1.53.0")]
394     pub const fn is_lt(self) -> bool {
395         matches!(self, Less)
396     }
397
398     /// Returns `true` if the ordering is the `Greater` variant.
399     ///
400     /// # Examples
401     ///
402     /// ```
403     /// use std::cmp::Ordering;
404     ///
405     /// assert_eq!(Ordering::Less.is_gt(), false);
406     /// assert_eq!(Ordering::Equal.is_gt(), false);
407     /// assert_eq!(Ordering::Greater.is_gt(), true);
408     /// ```
409     #[inline]
410     #[must_use]
411     #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
412     #[stable(feature = "ordering_helpers", since = "1.53.0")]
413     pub const fn is_gt(self) -> bool {
414         matches!(self, Greater)
415     }
416
417     /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
418     ///
419     /// # Examples
420     ///
421     /// ```
422     /// use std::cmp::Ordering;
423     ///
424     /// assert_eq!(Ordering::Less.is_le(), true);
425     /// assert_eq!(Ordering::Equal.is_le(), true);
426     /// assert_eq!(Ordering::Greater.is_le(), false);
427     /// ```
428     #[inline]
429     #[must_use]
430     #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
431     #[stable(feature = "ordering_helpers", since = "1.53.0")]
432     pub const fn is_le(self) -> bool {
433         !matches!(self, Greater)
434     }
435
436     /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
437     ///
438     /// # Examples
439     ///
440     /// ```
441     /// use std::cmp::Ordering;
442     ///
443     /// assert_eq!(Ordering::Less.is_ge(), false);
444     /// assert_eq!(Ordering::Equal.is_ge(), true);
445     /// assert_eq!(Ordering::Greater.is_ge(), true);
446     /// ```
447     #[inline]
448     #[must_use]
449     #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
450     #[stable(feature = "ordering_helpers", since = "1.53.0")]
451     pub const fn is_ge(self) -> bool {
452         !matches!(self, Less)
453     }
454
455     /// Reverses the `Ordering`.
456     ///
457     /// * `Less` becomes `Greater`.
458     /// * `Greater` becomes `Less`.
459     /// * `Equal` becomes `Equal`.
460     ///
461     /// # Examples
462     ///
463     /// Basic behavior:
464     ///
465     /// ```
466     /// use std::cmp::Ordering;
467     ///
468     /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
469     /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
470     /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
471     /// ```
472     ///
473     /// This method can be used to reverse a comparison:
474     ///
475     /// ```
476     /// let data: &mut [_] = &mut [2, 10, 5, 8];
477     ///
478     /// // sort the array from largest to smallest.
479     /// data.sort_by(|a, b| a.cmp(b).reverse());
480     ///
481     /// let b: &mut [_] = &mut [10, 8, 5, 2];
482     /// assert!(data == b);
483     /// ```
484     #[inline]
485     #[must_use]
486     #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
487     #[stable(feature = "rust1", since = "1.0.0")]
488     pub const fn reverse(self) -> Ordering {
489         match self {
490             Less => Greater,
491             Equal => Equal,
492             Greater => Less,
493         }
494     }
495
496     /// Chains two orderings.
497     ///
498     /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
499     ///
500     /// # Examples
501     ///
502     /// ```
503     /// use std::cmp::Ordering;
504     ///
505     /// let result = Ordering::Equal.then(Ordering::Less);
506     /// assert_eq!(result, Ordering::Less);
507     ///
508     /// let result = Ordering::Less.then(Ordering::Equal);
509     /// assert_eq!(result, Ordering::Less);
510     ///
511     /// let result = Ordering::Less.then(Ordering::Greater);
512     /// assert_eq!(result, Ordering::Less);
513     ///
514     /// let result = Ordering::Equal.then(Ordering::Equal);
515     /// assert_eq!(result, Ordering::Equal);
516     ///
517     /// let x: (i64, i64, i64) = (1, 2, 7);
518     /// let y: (i64, i64, i64) = (1, 5, 3);
519     /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
520     ///
521     /// assert_eq!(result, Ordering::Less);
522     /// ```
523     #[inline]
524     #[must_use]
525     #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
526     #[stable(feature = "ordering_chaining", since = "1.17.0")]
527     pub const fn then(self, other: Ordering) -> Ordering {
528         match self {
529             Equal => other,
530             _ => self,
531         }
532     }
533
534     /// Chains the ordering with the given function.
535     ///
536     /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
537     /// the result.
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// use std::cmp::Ordering;
543     ///
544     /// let result = Ordering::Equal.then_with(|| Ordering::Less);
545     /// assert_eq!(result, Ordering::Less);
546     ///
547     /// let result = Ordering::Less.then_with(|| Ordering::Equal);
548     /// assert_eq!(result, Ordering::Less);
549     ///
550     /// let result = Ordering::Less.then_with(|| Ordering::Greater);
551     /// assert_eq!(result, Ordering::Less);
552     ///
553     /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
554     /// assert_eq!(result, Ordering::Equal);
555     ///
556     /// let x: (i64, i64, i64) = (1, 2, 7);
557     /// let y: (i64, i64, i64) = (1, 5, 3);
558     /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
559     ///
560     /// assert_eq!(result, Ordering::Less);
561     /// ```
562     #[inline]
563     #[must_use]
564     #[stable(feature = "ordering_chaining", since = "1.17.0")]
565     pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
566         match self {
567             Equal => f(),
568             _ => self,
569         }
570     }
571 }
572
573 /// A helper struct for reverse ordering.
574 ///
575 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
576 /// can be used to reverse order a part of a key.
577 ///
578 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
579 ///
580 /// # Examples
581 ///
582 /// ```
583 /// use std::cmp::Reverse;
584 ///
585 /// let mut v = vec![1, 2, 3, 4, 5, 6];
586 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
587 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
588 /// ```
589 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
590 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
591 #[repr(transparent)]
592 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
593
594 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
595 impl<T: PartialOrd> PartialOrd for Reverse<T> {
596     #[inline]
597     fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
598         other.0.partial_cmp(&self.0)
599     }
600
601     #[inline]
602     fn lt(&self, other: &Self) -> bool {
603         other.0 < self.0
604     }
605     #[inline]
606     fn le(&self, other: &Self) -> bool {
607         other.0 <= self.0
608     }
609     #[inline]
610     fn gt(&self, other: &Self) -> bool {
611         other.0 > self.0
612     }
613     #[inline]
614     fn ge(&self, other: &Self) -> bool {
615         other.0 >= self.0
616     }
617 }
618
619 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
620 impl<T: Ord> Ord for Reverse<T> {
621     #[inline]
622     fn cmp(&self, other: &Reverse<T>) -> Ordering {
623         other.0.cmp(&self.0)
624     }
625 }
626
627 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
628 impl<T: Clone> Clone for Reverse<T> {
629     #[inline]
630     fn clone(&self) -> Reverse<T> {
631         Reverse(self.0.clone())
632     }
633
634     #[inline]
635     fn clone_from(&mut self, other: &Self) {
636         self.0.clone_from(&other.0)
637     }
638 }
639
640 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
641 ///
642 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
643 /// `max`, `min`, and `clamp` are consistent with `cmp`:
644 ///
645 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
646 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
647 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
648 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
649 ///   (ensured by the default implementation).
650 ///
651 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
652 /// deriving some of the traits and manually implementing others.
653 ///
654 /// ## Corollaries
655 ///
656 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
657 /// This means that for all `a`, `b` and `c`:
658 ///
659 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
660 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
661 ///
662 /// ## Derivable
663 ///
664 /// This trait can be used with `#[derive]`.
665 ///
666 /// When `derive`d on structs, it will produce a
667 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
668 /// based on the top-to-bottom declaration order of the struct's members.
669 ///
670 /// When `derive`d on enums, variants are ordered by their discriminants.
671 /// By default, the discriminant is smallest for variants at the top, and
672 /// largest for variants at the bottom. Here's an example:
673 ///
674 /// ```
675 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
676 /// enum E {
677 ///     Top,
678 ///     Bottom,
679 /// }
680 ///
681 /// assert!(E::Top < E::Bottom);
682 /// ```
683 ///
684 /// However, manually setting the discriminants can override this default
685 /// behavior:
686 ////
687 /// ```
688 /// #[derive(PartialEq, Eq, PartialOrd, Ord)]
689 /// enum E {
690 ///     Top = 2,
691 ///     Bottom = 1,
692 /// }
693 ///
694 /// assert!(E::Bottom < E::Top);
695 /// ```
696 ///
697 /// ## Lexicographical comparison
698 ///
699 /// Lexicographical comparison is an operation with the following properties:
700 ///  - Two sequences are compared element by element.
701 ///  - The first mismatching element defines which sequence is lexicographically less or greater than the other.
702 ///  - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
703 ///  - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
704 ///  - An empty sequence is lexicographically less than any non-empty sequence.
705 ///  - Two empty sequences are lexicographically equal.
706 ///
707 /// ## How can I implement `Ord`?
708 ///
709 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
710 ///
711 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
712 /// [`cmp`] on your type's fields.
713 ///
714 /// Here's an example where you want to sort people by height only, disregarding `id`
715 /// and `name`:
716 ///
717 /// ```
718 /// use std::cmp::Ordering;
719 ///
720 /// #[derive(Eq)]
721 /// struct Person {
722 ///     id: u32,
723 ///     name: String,
724 ///     height: u32,
725 /// }
726 ///
727 /// impl Ord for Person {
728 ///     fn cmp(&self, other: &Self) -> Ordering {
729 ///         self.height.cmp(&other.height)
730 ///     }
731 /// }
732 ///
733 /// impl PartialOrd for Person {
734 ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
735 ///         Some(self.cmp(other))
736 ///     }
737 /// }
738 ///
739 /// impl PartialEq for Person {
740 ///     fn eq(&self, other: &Self) -> bool {
741 ///         self.height == other.height
742 ///     }
743 /// }
744 /// ```
745 ///
746 /// [`cmp`]: Ord::cmp
747 #[doc(alias = "<")]
748 #[doc(alias = ">")]
749 #[doc(alias = "<=")]
750 #[doc(alias = ">=")]
751 #[stable(feature = "rust1", since = "1.0.0")]
752 #[rustc_diagnostic_item = "Ord"]
753 pub trait Ord: Eq + PartialOrd<Self> {
754     /// This method returns an [`Ordering`] between `self` and `other`.
755     ///
756     /// By convention, `self.cmp(&other)` returns the ordering matching the expression
757     /// `self <operator> other` if true.
758     ///
759     /// # Examples
760     ///
761     /// ```
762     /// use std::cmp::Ordering;
763     ///
764     /// assert_eq!(5.cmp(&10), Ordering::Less);
765     /// assert_eq!(10.cmp(&5), Ordering::Greater);
766     /// assert_eq!(5.cmp(&5), Ordering::Equal);
767     /// ```
768     #[must_use]
769     #[stable(feature = "rust1", since = "1.0.0")]
770     fn cmp(&self, other: &Self) -> Ordering;
771
772     /// Compares and returns the maximum of two values.
773     ///
774     /// Returns the second argument if the comparison determines them to be equal.
775     ///
776     /// # Examples
777     ///
778     /// ```
779     /// assert_eq!(2, 1.max(2));
780     /// assert_eq!(2, 2.max(2));
781     /// ```
782     #[stable(feature = "ord_max_min", since = "1.21.0")]
783     #[inline]
784     #[must_use]
785     fn max(self, other: Self) -> Self
786     where
787         Self: Sized,
788     {
789         max_by(self, other, Ord::cmp)
790     }
791
792     /// Compares and returns the minimum of two values.
793     ///
794     /// Returns the first argument if the comparison determines them to be equal.
795     ///
796     /// # Examples
797     ///
798     /// ```
799     /// assert_eq!(1, 1.min(2));
800     /// assert_eq!(2, 2.min(2));
801     /// ```
802     #[stable(feature = "ord_max_min", since = "1.21.0")]
803     #[inline]
804     #[must_use]
805     fn min(self, other: Self) -> Self
806     where
807         Self: Sized,
808     {
809         min_by(self, other, Ord::cmp)
810     }
811
812     /// Restrict a value to a certain interval.
813     ///
814     /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
815     /// less than `min`. Otherwise this returns `self`.
816     ///
817     /// # Panics
818     ///
819     /// Panics if `min > max`.
820     ///
821     /// # Examples
822     ///
823     /// ```
824     /// assert!((-3).clamp(-2, 1) == -2);
825     /// assert!(0.clamp(-2, 1) == 0);
826     /// assert!(2.clamp(-2, 1) == 1);
827     /// ```
828     #[must_use]
829     #[stable(feature = "clamp", since = "1.50.0")]
830     fn clamp(self, min: Self, max: Self) -> Self
831     where
832         Self: Sized,
833     {
834         assert!(min <= max);
835         if self < min {
836             min
837         } else if self > max {
838             max
839         } else {
840             self
841         }
842     }
843 }
844
845 /// Derive macro generating an impl of the trait `Ord`.
846 #[rustc_builtin_macro]
847 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
848 #[allow_internal_unstable(core_intrinsics)]
849 pub macro Ord($item:item) {
850     /* compiler built-in */
851 }
852
853 #[stable(feature = "rust1", since = "1.0.0")]
854 impl Eq for Ordering {}
855
856 #[stable(feature = "rust1", since = "1.0.0")]
857 impl Ord for Ordering {
858     #[inline]
859     fn cmp(&self, other: &Ordering) -> Ordering {
860         (*self as i32).cmp(&(*other as i32))
861     }
862 }
863
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl PartialOrd for Ordering {
866     #[inline]
867     fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
868         (*self as i32).partial_cmp(&(*other as i32))
869     }
870 }
871
872 /// Trait for values that can be compared for a sort-order.
873 ///
874 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
875 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
876 ///
877 /// The methods of this trait must be consistent with each other and with those of `PartialEq` in
878 /// the following sense:
879 ///
880 /// - `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
881 /// - `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
882 ///   (ensured by the default implementation).
883 /// - `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
884 ///   (ensured by the default implementation).
885 /// - `a <= b` if and only if `a < b || a == b`
886 ///   (ensured by the default implementation).
887 /// - `a >= b` if and only if `a > b || a == b`
888 ///   (ensured by the default implementation).
889 /// - `a != b` if and only if `!(a == b)` (already part of `PartialEq`).
890 ///
891 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
892 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
893 /// easy to accidentally make them disagree by deriving some of the traits and manually
894 /// implementing others.
895 ///
896 /// The comparison must satisfy, for all `a`, `b` and `c`:
897 ///
898 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
899 /// - duality: `a < b` if and only if `b > a`.
900 ///
901 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
902 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
903 /// PartialOrd<V>`.
904 ///
905 /// ## Corollaries
906 ///
907 /// The following corollaries follow from the above requirements:
908 ///
909 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
910 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
911 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
912 ///
913 /// ## Derivable
914 ///
915 /// This trait can be used with `#[derive]`.
916 ///
917 /// When `derive`d on structs, it will produce a
918 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
919 /// based on the top-to-bottom declaration order of the struct's members.
920 ///
921 /// When `derive`d on enums, variants are ordered by their discriminants.
922 /// By default, the discriminant is smallest for variants at the top, and
923 /// largest for variants at the bottom. Here's an example:
924 ///
925 /// ```
926 /// #[derive(PartialEq, PartialOrd)]
927 /// enum E {
928 ///     Top,
929 ///     Bottom,
930 /// }
931 ///
932 /// assert!(E::Top < E::Bottom);
933 /// ```
934 ///
935 /// However, manually setting the discriminants can override this default
936 /// behavior:
937 ////
938 /// ```
939 /// #[derive(PartialEq, PartialOrd)]
940 /// enum E {
941 ///     Top = 2,
942 ///     Bottom = 1,
943 /// }
944 ///
945 /// assert!(E::Bottom < E::Top);
946 /// ```
947 ///
948 /// ## How can I implement `PartialOrd`?
949 ///
950 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
951 /// generated from default implementations.
952 ///
953 /// However it remains possible to implement the others separately for types which do not have a
954 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
955 /// false` (cf. IEEE 754-2008 section 5.11).
956 ///
957 /// `PartialOrd` requires your type to be [`PartialEq`].
958 ///
959 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
960 ///
961 /// ```
962 /// use std::cmp::Ordering;
963 ///
964 /// #[derive(Eq)]
965 /// struct Person {
966 ///     id: u32,
967 ///     name: String,
968 ///     height: u32,
969 /// }
970 ///
971 /// impl PartialOrd for Person {
972 ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
973 ///         Some(self.cmp(other))
974 ///     }
975 /// }
976 ///
977 /// impl Ord for Person {
978 ///     fn cmp(&self, other: &Self) -> Ordering {
979 ///         self.height.cmp(&other.height)
980 ///     }
981 /// }
982 ///
983 /// impl PartialEq for Person {
984 ///     fn eq(&self, other: &Self) -> bool {
985 ///         self.height == other.height
986 ///     }
987 /// }
988 /// ```
989 ///
990 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
991 /// is an example of `Person` types who have a floating-point `height` field that
992 /// is the only field to be used for sorting:
993 ///
994 /// ```
995 /// use std::cmp::Ordering;
996 ///
997 /// struct Person {
998 ///     id: u32,
999 ///     name: String,
1000 ///     height: f64,
1001 /// }
1002 ///
1003 /// impl PartialOrd for Person {
1004 ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1005 ///         self.height.partial_cmp(&other.height)
1006 ///     }
1007 /// }
1008 ///
1009 /// impl PartialEq for Person {
1010 ///     fn eq(&self, other: &Self) -> bool {
1011 ///         self.height == other.height
1012 ///     }
1013 /// }
1014 /// ```
1015 ///
1016 /// # Examples
1017 ///
1018 /// ```
1019 /// let x: u32 = 0;
1020 /// let y: u32 = 1;
1021 ///
1022 /// assert_eq!(x < y, true);
1023 /// assert_eq!(x.lt(&y), true);
1024 /// ```
1025 ///
1026 /// [`partial_cmp`]: PartialOrd::partial_cmp
1027 /// [`cmp`]: Ord::cmp
1028 #[lang = "partial_ord"]
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 #[doc(alias = ">")]
1031 #[doc(alias = "<")]
1032 #[doc(alias = "<=")]
1033 #[doc(alias = ">=")]
1034 #[rustc_on_unimplemented(
1035     message = "can't compare `{Self}` with `{Rhs}`",
1036     label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
1037 )]
1038 #[rustc_diagnostic_item = "PartialOrd"]
1039 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
1040     /// This method returns an ordering between `self` and `other` values if one exists.
1041     ///
1042     /// # Examples
1043     ///
1044     /// ```
1045     /// use std::cmp::Ordering;
1046     ///
1047     /// let result = 1.0.partial_cmp(&2.0);
1048     /// assert_eq!(result, Some(Ordering::Less));
1049     ///
1050     /// let result = 1.0.partial_cmp(&1.0);
1051     /// assert_eq!(result, Some(Ordering::Equal));
1052     ///
1053     /// let result = 2.0.partial_cmp(&1.0);
1054     /// assert_eq!(result, Some(Ordering::Greater));
1055     /// ```
1056     ///
1057     /// When comparison is impossible:
1058     ///
1059     /// ```
1060     /// let result = f64::NAN.partial_cmp(&1.0);
1061     /// assert_eq!(result, None);
1062     /// ```
1063     #[must_use]
1064     #[stable(feature = "rust1", since = "1.0.0")]
1065     fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1066
1067     /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1068     ///
1069     /// # Examples
1070     ///
1071     /// ```
1072     /// let result = 1.0 < 2.0;
1073     /// assert_eq!(result, true);
1074     ///
1075     /// let result = 2.0 < 1.0;
1076     /// assert_eq!(result, false);
1077     /// ```
1078     #[inline]
1079     #[must_use]
1080     #[stable(feature = "rust1", since = "1.0.0")]
1081     #[default_method_body_is_const]
1082     fn lt(&self, other: &Rhs) -> bool {
1083         matches!(self.partial_cmp(other), Some(Less))
1084     }
1085
1086     /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1087     /// operator.
1088     ///
1089     /// # Examples
1090     ///
1091     /// ```
1092     /// let result = 1.0 <= 2.0;
1093     /// assert_eq!(result, true);
1094     ///
1095     /// let result = 2.0 <= 2.0;
1096     /// assert_eq!(result, true);
1097     /// ```
1098     #[inline]
1099     #[must_use]
1100     #[stable(feature = "rust1", since = "1.0.0")]
1101     #[default_method_body_is_const]
1102     fn le(&self, other: &Rhs) -> bool {
1103         // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`.
1104         // FIXME: The root cause was fixed upstream in LLVM with:
1105         // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775
1106         // Revert this workaround once support for LLVM 12 gets dropped.
1107         !matches!(self.partial_cmp(other), None | Some(Greater))
1108     }
1109
1110     /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1111     ///
1112     /// # Examples
1113     ///
1114     /// ```
1115     /// let result = 1.0 > 2.0;
1116     /// assert_eq!(result, false);
1117     ///
1118     /// let result = 2.0 > 2.0;
1119     /// assert_eq!(result, false);
1120     /// ```
1121     #[inline]
1122     #[must_use]
1123     #[stable(feature = "rust1", since = "1.0.0")]
1124     #[default_method_body_is_const]
1125     fn gt(&self, other: &Rhs) -> bool {
1126         matches!(self.partial_cmp(other), Some(Greater))
1127     }
1128
1129     /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1130     /// operator.
1131     ///
1132     /// # Examples
1133     ///
1134     /// ```
1135     /// let result = 2.0 >= 1.0;
1136     /// assert_eq!(result, true);
1137     ///
1138     /// let result = 2.0 >= 2.0;
1139     /// assert_eq!(result, true);
1140     /// ```
1141     #[inline]
1142     #[must_use]
1143     #[stable(feature = "rust1", since = "1.0.0")]
1144     #[default_method_body_is_const]
1145     fn ge(&self, other: &Rhs) -> bool {
1146         matches!(self.partial_cmp(other), Some(Greater | Equal))
1147     }
1148 }
1149
1150 /// Derive macro generating an impl of the trait `PartialOrd`.
1151 #[rustc_builtin_macro]
1152 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1153 #[allow_internal_unstable(core_intrinsics)]
1154 pub macro PartialOrd($item:item) {
1155     /* compiler built-in */
1156 }
1157
1158 /// Compares and returns the minimum of two values.
1159 ///
1160 /// Returns the first argument if the comparison determines them to be equal.
1161 ///
1162 /// Internally uses an alias to [`Ord::min`].
1163 ///
1164 /// # Examples
1165 ///
1166 /// ```
1167 /// use std::cmp;
1168 ///
1169 /// assert_eq!(1, cmp::min(1, 2));
1170 /// assert_eq!(2, cmp::min(2, 2));
1171 /// ```
1172 #[inline]
1173 #[must_use]
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1176 pub fn min<T: Ord>(v1: T, v2: T) -> T {
1177     v1.min(v2)
1178 }
1179
1180 /// Returns the minimum of two values with respect to the specified comparison function.
1181 ///
1182 /// Returns the first argument if the comparison determines them to be equal.
1183 ///
1184 /// # Examples
1185 ///
1186 /// ```
1187 /// use std::cmp;
1188 ///
1189 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1190 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1191 /// ```
1192 #[inline]
1193 #[must_use]
1194 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1195 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1196     match compare(&v1, &v2) {
1197         Ordering::Less | Ordering::Equal => v1,
1198         Ordering::Greater => v2,
1199     }
1200 }
1201
1202 /// Returns the element that gives the minimum value from the specified function.
1203 ///
1204 /// Returns the first argument if the comparison determines them to be equal.
1205 ///
1206 /// # Examples
1207 ///
1208 /// ```
1209 /// use std::cmp;
1210 ///
1211 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1212 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1213 /// ```
1214 #[inline]
1215 #[must_use]
1216 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1217 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1218     min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1219 }
1220
1221 /// Compares and returns the maximum of two values.
1222 ///
1223 /// Returns the second argument if the comparison determines them to be equal.
1224 ///
1225 /// Internally uses an alias to [`Ord::max`].
1226 ///
1227 /// # Examples
1228 ///
1229 /// ```
1230 /// use std::cmp;
1231 ///
1232 /// assert_eq!(2, cmp::max(1, 2));
1233 /// assert_eq!(2, cmp::max(2, 2));
1234 /// ```
1235 #[inline]
1236 #[must_use]
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1239 pub fn max<T: Ord>(v1: T, v2: T) -> T {
1240     v1.max(v2)
1241 }
1242
1243 /// Returns the maximum of two values with respect to the specified comparison function.
1244 ///
1245 /// Returns the second argument if the comparison determines them to be equal.
1246 ///
1247 /// # Examples
1248 ///
1249 /// ```
1250 /// use std::cmp;
1251 ///
1252 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1253 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1254 /// ```
1255 #[inline]
1256 #[must_use]
1257 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1258 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1259     match compare(&v1, &v2) {
1260         Ordering::Less | Ordering::Equal => v2,
1261         Ordering::Greater => v1,
1262     }
1263 }
1264
1265 /// Returns the element that gives the maximum value from the specified function.
1266 ///
1267 /// Returns the second argument if the comparison determines them to be equal.
1268 ///
1269 /// # Examples
1270 ///
1271 /// ```
1272 /// use std::cmp;
1273 ///
1274 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1275 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1276 /// ```
1277 #[inline]
1278 #[must_use]
1279 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1280 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1281     max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1282 }
1283
1284 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1285 mod impls {
1286     use crate::cmp::Ordering::{self, Equal, Greater, Less};
1287     use crate::hint::unreachable_unchecked;
1288
1289     macro_rules! partial_eq_impl {
1290         ($($t:ty)*) => ($(
1291             #[stable(feature = "rust1", since = "1.0.0")]
1292             impl PartialEq for $t {
1293                 #[inline]
1294                 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1295                 #[inline]
1296                 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1297             }
1298         )*)
1299     }
1300
1301     #[stable(feature = "rust1", since = "1.0.0")]
1302     impl PartialEq for () {
1303         #[inline]
1304         fn eq(&self, _other: &()) -> bool {
1305             true
1306         }
1307         #[inline]
1308         fn ne(&self, _other: &()) -> bool {
1309             false
1310         }
1311     }
1312
1313     partial_eq_impl! {
1314         bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1315     }
1316
1317     macro_rules! eq_impl {
1318         ($($t:ty)*) => ($(
1319             #[stable(feature = "rust1", since = "1.0.0")]
1320             impl Eq for $t {}
1321         )*)
1322     }
1323
1324     eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1325
1326     macro_rules! partial_ord_impl {
1327         ($($t:ty)*) => ($(
1328             #[stable(feature = "rust1", since = "1.0.0")]
1329             impl PartialOrd for $t {
1330                 #[inline]
1331                 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1332                     match (self <= other, self >= other) {
1333                         (false, false) => None,
1334                         (false, true) => Some(Greater),
1335                         (true, false) => Some(Less),
1336                         (true, true) => Some(Equal),
1337                     }
1338                 }
1339                 #[inline]
1340                 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1341                 #[inline]
1342                 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1343                 #[inline]
1344                 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1345                 #[inline]
1346                 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1347             }
1348         )*)
1349     }
1350
1351     #[stable(feature = "rust1", since = "1.0.0")]
1352     impl PartialOrd for () {
1353         #[inline]
1354         fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1355             Some(Equal)
1356         }
1357     }
1358
1359     #[stable(feature = "rust1", since = "1.0.0")]
1360     impl PartialOrd for bool {
1361         #[inline]
1362         fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1363             Some(self.cmp(other))
1364         }
1365     }
1366
1367     partial_ord_impl! { f32 f64 }
1368
1369     macro_rules! ord_impl {
1370         ($($t:ty)*) => ($(
1371             #[stable(feature = "rust1", since = "1.0.0")]
1372             impl PartialOrd for $t {
1373                 #[inline]
1374                 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1375                     Some(self.cmp(other))
1376                 }
1377                 #[inline]
1378                 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1379                 #[inline]
1380                 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1381                 #[inline]
1382                 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1383                 #[inline]
1384                 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1385             }
1386
1387             #[stable(feature = "rust1", since = "1.0.0")]
1388             impl Ord for $t {
1389                 #[inline]
1390                 fn cmp(&self, other: &$t) -> Ordering {
1391                     // The order here is important to generate more optimal assembly.
1392                     // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1393                     if *self < *other { Less }
1394                     else if *self == *other { Equal }
1395                     else { Greater }
1396                 }
1397             }
1398         )*)
1399     }
1400
1401     #[stable(feature = "rust1", since = "1.0.0")]
1402     impl Ord for () {
1403         #[inline]
1404         fn cmp(&self, _other: &()) -> Ordering {
1405             Equal
1406         }
1407     }
1408
1409     #[stable(feature = "rust1", since = "1.0.0")]
1410     impl Ord for bool {
1411         #[inline]
1412         fn cmp(&self, other: &bool) -> Ordering {
1413             // Casting to i8's and converting the difference to an Ordering generates
1414             // more optimal assembly.
1415             // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1416             match (*self as i8) - (*other as i8) {
1417                 -1 => Less,
1418                 0 => Equal,
1419                 1 => Greater,
1420                 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1421                 _ => unsafe { unreachable_unchecked() },
1422             }
1423         }
1424     }
1425
1426     ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1427
1428     #[unstable(feature = "never_type", issue = "35121")]
1429     impl PartialEq for ! {
1430         fn eq(&self, _: &!) -> bool {
1431             *self
1432         }
1433     }
1434
1435     #[unstable(feature = "never_type", issue = "35121")]
1436     impl Eq for ! {}
1437
1438     #[unstable(feature = "never_type", issue = "35121")]
1439     impl PartialOrd for ! {
1440         fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1441             *self
1442         }
1443     }
1444
1445     #[unstable(feature = "never_type", issue = "35121")]
1446     impl Ord for ! {
1447         fn cmp(&self, _: &!) -> Ordering {
1448             *self
1449         }
1450     }
1451
1452     // & pointers
1453
1454     #[stable(feature = "rust1", since = "1.0.0")]
1455     impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
1456     where
1457         A: PartialEq<B>,
1458     {
1459         #[inline]
1460         fn eq(&self, other: &&B) -> bool {
1461             PartialEq::eq(*self, *other)
1462         }
1463         #[inline]
1464         fn ne(&self, other: &&B) -> bool {
1465             PartialEq::ne(*self, *other)
1466         }
1467     }
1468     #[stable(feature = "rust1", since = "1.0.0")]
1469     impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1470     where
1471         A: PartialOrd<B>,
1472     {
1473         #[inline]
1474         fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1475             PartialOrd::partial_cmp(*self, *other)
1476         }
1477         #[inline]
1478         fn lt(&self, other: &&B) -> bool {
1479             PartialOrd::lt(*self, *other)
1480         }
1481         #[inline]
1482         fn le(&self, other: &&B) -> bool {
1483             PartialOrd::le(*self, *other)
1484         }
1485         #[inline]
1486         fn gt(&self, other: &&B) -> bool {
1487             PartialOrd::gt(*self, *other)
1488         }
1489         #[inline]
1490         fn ge(&self, other: &&B) -> bool {
1491             PartialOrd::ge(*self, *other)
1492         }
1493     }
1494     #[stable(feature = "rust1", since = "1.0.0")]
1495     impl<A: ?Sized> Ord for &A
1496     where
1497         A: Ord,
1498     {
1499         #[inline]
1500         fn cmp(&self, other: &Self) -> Ordering {
1501             Ord::cmp(*self, *other)
1502         }
1503     }
1504     #[stable(feature = "rust1", since = "1.0.0")]
1505     impl<A: ?Sized> Eq for &A where A: Eq {}
1506
1507     // &mut pointers
1508
1509     #[stable(feature = "rust1", since = "1.0.0")]
1510     impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1511     where
1512         A: PartialEq<B>,
1513     {
1514         #[inline]
1515         fn eq(&self, other: &&mut B) -> bool {
1516             PartialEq::eq(*self, *other)
1517         }
1518         #[inline]
1519         fn ne(&self, other: &&mut B) -> bool {
1520             PartialEq::ne(*self, *other)
1521         }
1522     }
1523     #[stable(feature = "rust1", since = "1.0.0")]
1524     impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1525     where
1526         A: PartialOrd<B>,
1527     {
1528         #[inline]
1529         fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1530             PartialOrd::partial_cmp(*self, *other)
1531         }
1532         #[inline]
1533         fn lt(&self, other: &&mut B) -> bool {
1534             PartialOrd::lt(*self, *other)
1535         }
1536         #[inline]
1537         fn le(&self, other: &&mut B) -> bool {
1538             PartialOrd::le(*self, *other)
1539         }
1540         #[inline]
1541         fn gt(&self, other: &&mut B) -> bool {
1542             PartialOrd::gt(*self, *other)
1543         }
1544         #[inline]
1545         fn ge(&self, other: &&mut B) -> bool {
1546             PartialOrd::ge(*self, *other)
1547         }
1548     }
1549     #[stable(feature = "rust1", since = "1.0.0")]
1550     impl<A: ?Sized> Ord for &mut A
1551     where
1552         A: Ord,
1553     {
1554         #[inline]
1555         fn cmp(&self, other: &Self) -> Ordering {
1556             Ord::cmp(*self, *other)
1557         }
1558     }
1559     #[stable(feature = "rust1", since = "1.0.0")]
1560     impl<A: ?Sized> Eq for &mut A where A: Eq {}
1561
1562     #[stable(feature = "rust1", since = "1.0.0")]
1563     impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1564     where
1565         A: PartialEq<B>,
1566     {
1567         #[inline]
1568         fn eq(&self, other: &&mut B) -> bool {
1569             PartialEq::eq(*self, *other)
1570         }
1571         #[inline]
1572         fn ne(&self, other: &&mut B) -> bool {
1573             PartialEq::ne(*self, *other)
1574         }
1575     }
1576
1577     #[stable(feature = "rust1", since = "1.0.0")]
1578     impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1579     where
1580         A: PartialEq<B>,
1581     {
1582         #[inline]
1583         fn eq(&self, other: &&B) -> bool {
1584             PartialEq::eq(*self, *other)
1585         }
1586         #[inline]
1587         fn ne(&self, other: &&B) -> bool {
1588             PartialEq::ne(*self, *other)
1589         }
1590     }
1591 }