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