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