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