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