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