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