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