core/
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//! * [`PartialEq<Rhs>`] overloads the `==` and `!=` operators. In cases where
7//!   `Rhs` (the right hand side's type) is `Self`, this trait corresponds to a
8//!   partial equivalence relation.
9//! * [`Eq`] indicates that the overloaded `==` operator corresponds to an
10//!   equivalence relation.
11//! * [`Ord`] and [`PartialOrd`] are traits that allow you to define total and
12//!   partial orderings between values, respectively. Implementing them overloads
13//!   the `<`, `<=`, `>`, and `>=` operators.
14//! * [`Ordering`] is an enum returned by the main functions of [`Ord`] and
15//!   [`PartialOrd`], and describes an ordering of two values (less, equal, or
16//!   greater).
17//! * [`Reverse`] is a struct that allows you to easily reverse an ordering.
18//! * [`max`] and [`min`] are functions that build off of [`Ord`] and allow you
19//!   to find the maximum or minimum of two values.
20//!
21//! For more details, see the respective documentation of each item in the list.
22//!
23//! [`max`]: Ord::max
24//! [`min`]: Ord::min
25
26#![stable(feature = "rust1", since = "1.0.0")]
27
28mod bytewise;
29pub(crate) use bytewise::BytewiseEq;
30
31use self::Ordering::*;
32use crate::marker::{Destruct, PointeeSized};
33use crate::ops::ControlFlow;
34
35/// Trait for comparisons using the equality operator.
36///
37/// Implementing this trait for types provides the `==` and `!=` operators for
38/// those types.
39///
40/// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
41/// We use the easier-to-read infix notation in the remainder of this documentation.
42///
43/// This trait allows for comparisons using the equality operator, for types
44/// that do not have a full equivalence relation. For example, in floating point
45/// numbers `NaN != NaN`, so floating point types implement `PartialEq` but not
46/// [`trait@Eq`]. Formally speaking, when `Rhs == Self`, this trait corresponds
47/// to a [partial equivalence relation].
48///
49/// [partial equivalence relation]: https://en.wikipedia.org/wiki/Partial_equivalence_relation
50///
51/// Implementations must ensure that `eq` and `ne` are consistent with each other:
52///
53/// - `a != b` if and only if `!(a == b)`.
54///
55/// The default implementation of `ne` provides this consistency and is almost
56/// always sufficient. It should not be overridden without very good reason.
57///
58/// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
59/// be consistent with `PartialEq` (see the documentation of those traits for the exact
60/// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
61/// manually implementing others.
62///
63/// The equality relation `==` must satisfy the following conditions
64/// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
65///
66/// - **Symmetry**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
67///   implies `b == a`**; and
68///
69/// - **Transitivity**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
70///   PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
71///   This must also work for longer chains, such as when `A: PartialEq<B>`, `B: PartialEq<C>`,
72///   `C: PartialEq<D>`, and `A: PartialEq<D>` all exist.
73///
74/// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
75/// (transitive) impls are not forced to exist, but these requirements apply
76/// whenever they do exist.
77///
78/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
79/// specified, but users of the trait must ensure that such logic errors do *not* result in
80/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
81/// methods.
82///
83/// ## Cross-crate considerations
84///
85/// Upholding the requirements stated above can become tricky when one crate implements `PartialEq`
86/// for a type of another crate (i.e., to allow comparing one of its own types with a type from the
87/// standard library). The recommendation is to never implement this trait for a foreign type. In
88/// other words, such a crate should do `impl PartialEq<ForeignType> for LocalType`, but it should
89/// *not* do `impl PartialEq<LocalType> for ForeignType`.
90///
91/// This avoids the problem of transitive chains that criss-cross crate boundaries: for all local
92/// types `T`, you may assume that no other crate will add `impl`s that allow comparing `T == U`. In
93/// other words, if other crates add `impl`s that allow building longer transitive chains `U1 == ...
94/// == T == V1 == ...`, then all the types that appear to the right of `T` must be types that the
95/// crate defining `T` already knows about. This rules out transitive chains where downstream crates
96/// can add new `impl`s that "stitch together" comparisons of foreign types in ways that violate
97/// transitivity.
98///
99/// Not having such foreign `impl`s also avoids forward compatibility issues where one crate adding
100/// more `PartialEq` implementations can cause build failures in downstream crates.
101///
102/// ## Derivable
103///
104/// This trait can be used with `#[derive]`. When `derive`d on structs, two
105/// instances are equal if all fields are equal, and not equal if any fields
106/// are not equal. When `derive`d on enums, two instances are equal if they
107/// are the same variant and all fields are equal.
108///
109/// ## How can I implement `PartialEq`?
110///
111/// An example implementation for a domain in which two books are considered
112/// the same book if their ISBN matches, even if the formats differ:
113///
114/// ```
115/// enum BookFormat {
116///     Paperback,
117///     Hardback,
118///     Ebook,
119/// }
120///
121/// struct Book {
122///     isbn: i32,
123///     format: BookFormat,
124/// }
125///
126/// impl PartialEq for Book {
127///     fn eq(&self, other: &Self) -> bool {
128///         self.isbn == other.isbn
129///     }
130/// }
131///
132/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
133/// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
134/// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
135///
136/// assert!(b1 == b2);
137/// assert!(b1 != b3);
138/// ```
139///
140/// ## How can I compare two different types?
141///
142/// The type you can compare with is controlled by `PartialEq`'s type parameter.
143/// For example, let's tweak our previous code a bit:
144///
145/// ```
146/// // The derive implements <BookFormat> == <BookFormat> comparisons
147/// #[derive(PartialEq)]
148/// enum BookFormat {
149///     Paperback,
150///     Hardback,
151///     Ebook,
152/// }
153///
154/// struct Book {
155///     isbn: i32,
156///     format: BookFormat,
157/// }
158///
159/// // Implement <Book> == <BookFormat> comparisons
160/// impl PartialEq<BookFormat> for Book {
161///     fn eq(&self, other: &BookFormat) -> bool {
162///         self.format == *other
163///     }
164/// }
165///
166/// // Implement <BookFormat> == <Book> comparisons
167/// impl PartialEq<Book> for BookFormat {
168///     fn eq(&self, other: &Book) -> bool {
169///         *self == other.format
170///     }
171/// }
172///
173/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
174///
175/// assert!(b1 == BookFormat::Paperback);
176/// assert!(BookFormat::Ebook != b1);
177/// ```
178///
179/// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
180/// we allow `BookFormat`s to be compared with `Book`s.
181///
182/// A comparison like the one above, which ignores some fields of the struct,
183/// can be dangerous. It can easily lead to an unintended violation of the
184/// requirements for a partial equivalence relation. For example, if we kept
185/// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
186/// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
187/// via the manual implementation from the first example) then the result would
188/// violate transitivity:
189///
190/// ```should_panic
191/// #[derive(PartialEq)]
192/// enum BookFormat {
193///     Paperback,
194///     Hardback,
195///     Ebook,
196/// }
197///
198/// #[derive(PartialEq)]
199/// struct Book {
200///     isbn: i32,
201///     format: BookFormat,
202/// }
203///
204/// impl PartialEq<BookFormat> for Book {
205///     fn eq(&self, other: &BookFormat) -> bool {
206///         self.format == *other
207///     }
208/// }
209///
210/// impl PartialEq<Book> for BookFormat {
211///     fn eq(&self, other: &Book) -> bool {
212///         *self == other.format
213///     }
214/// }
215///
216/// fn main() {
217///     let b1 = Book { isbn: 1, format: BookFormat::Paperback };
218///     let b2 = Book { isbn: 2, format: BookFormat::Paperback };
219///
220///     assert!(b1 == BookFormat::Paperback);
221///     assert!(BookFormat::Paperback == b2);
222///
223///     // The following should hold by transitivity but doesn't.
224///     assert!(b1 == b2); // <-- PANICS
225/// }
226/// ```
227///
228/// # Examples
229///
230/// ```
231/// let x: u32 = 0;
232/// let y: u32 = 1;
233///
234/// assert_eq!(x == y, false);
235/// assert_eq!(x.eq(&y), false);
236/// ```
237///
238/// [`eq`]: PartialEq::eq
239/// [`ne`]: PartialEq::ne
240#[lang = "eq"]
241#[stable(feature = "rust1", since = "1.0.0")]
242#[doc(alias = "==")]
243#[doc(alias = "!=")]
244#[rustc_on_unimplemented(
245    message = "can't compare `{Self}` with `{Rhs}`",
246    label = "no implementation for `{Self} == {Rhs}`",
247    append_const_msg
248)]
249#[rustc_diagnostic_item = "PartialEq"]
250#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
251pub const trait PartialEq<Rhs: PointeeSized = Self>: PointeeSized {
252    /// Tests for `self` and `other` values to be equal, and is used by `==`.
253    #[must_use]
254    #[stable(feature = "rust1", since = "1.0.0")]
255    #[rustc_diagnostic_item = "cmp_partialeq_eq"]
256    fn eq(&self, other: &Rhs) -> bool;
257
258    /// Tests for `!=`. The default implementation is almost always sufficient,
259    /// and should not be overridden without very good reason.
260    #[inline]
261    #[must_use]
262    #[stable(feature = "rust1", since = "1.0.0")]
263    #[rustc_diagnostic_item = "cmp_partialeq_ne"]
264    fn ne(&self, other: &Rhs) -> bool {
265        !self.eq(other)
266    }
267}
268
269/// Derive macro generating an impl of the trait [`PartialEq`].
270/// The behavior of this macro is described in detail [here](PartialEq#derivable).
271#[rustc_builtin_macro]
272#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
273#[allow_internal_unstable(core_intrinsics, structural_match)]
274pub macro PartialEq($item:item) {
275    /* compiler built-in */
276}
277
278/// Trait for comparisons corresponding to [equivalence relations](
279/// https://en.wikipedia.org/wiki/Equivalence_relation).
280///
281/// The primary difference to [`PartialEq`] is the additional requirement for reflexivity. A type
282/// that implements [`PartialEq`] guarantees that for all `a`, `b` and `c`:
283///
284/// - symmetric: `a == b` implies `b == a` and `a != b` implies `!(a == b)`
285/// - transitive: `a == b` and `b == c` implies `a == c`
286///
287/// `Eq`, which builds on top of [`PartialEq`] also implies:
288///
289/// - reflexive: `a == a`
290///
291/// This property cannot be checked by the compiler, and therefore `Eq` is a trait without methods.
292///
293/// Violating this property is a logic error. The behavior resulting from a logic error is not
294/// specified, but users of the trait must ensure that such logic errors do *not* result in
295/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
296/// methods.
297///
298/// Floating point types such as [`f32`] and [`f64`] implement only [`PartialEq`] but *not* `Eq`
299/// because `NaN` != `NaN`.
300///
301/// ## Derivable
302///
303/// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has no extra methods, it
304/// is only informing the compiler that this is an equivalence relation rather than a partial
305/// equivalence relation. Note that the `derive` strategy requires all fields are `Eq`, which isn't
306/// always desired.
307///
308/// ## How can I implement `Eq`?
309///
310/// If you cannot use the `derive` strategy, specify that your type implements `Eq`, which has no
311/// extra methods:
312///
313/// ```
314/// enum BookFormat {
315///     Paperback,
316///     Hardback,
317///     Ebook,
318/// }
319///
320/// struct Book {
321///     isbn: i32,
322///     format: BookFormat,
323/// }
324///
325/// impl PartialEq for Book {
326///     fn eq(&self, other: &Self) -> bool {
327///         self.isbn == other.isbn
328///     }
329/// }
330///
331/// impl Eq for Book {}
332/// ```
333#[doc(alias = "==")]
334#[doc(alias = "!=")]
335#[stable(feature = "rust1", since = "1.0.0")]
336#[rustc_diagnostic_item = "Eq"]
337#[const_trait]
338#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
339pub trait Eq: [const] PartialEq<Self> + PointeeSized {
340    // this method is used solely by `impl Eq or #[derive(Eq)]` to assert that every component of a
341    // type implements `Eq` itself. The current deriving infrastructure means doing this assertion
342    // without using a method on this trait is nearly impossible.
343    //
344    // This should never be implemented by hand.
345    #[doc(hidden)]
346    #[coverage(off)]
347    #[inline]
348    #[stable(feature = "rust1", since = "1.0.0")]
349    fn assert_receiver_is_total_eq(&self) {}
350}
351
352/// Derive macro generating an impl of the trait [`Eq`].
353#[rustc_builtin_macro]
354#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
355#[allow_internal_unstable(core_intrinsics, derive_eq, structural_match)]
356#[allow_internal_unstable(coverage_attribute)]
357pub macro Eq($item:item) {
358    /* compiler built-in */
359}
360
361// FIXME: this struct is used solely by #[derive] to
362// assert that every component of a type implements Eq.
363//
364// This struct should never appear in user code.
365#[doc(hidden)]
366#[allow(missing_debug_implementations)]
367#[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
368pub struct AssertParamIsEq<T: Eq + PointeeSized> {
369    _field: crate::marker::PhantomData<T>,
370}
371
372/// An `Ordering` is the result of a comparison between two values.
373///
374/// # Examples
375///
376/// ```
377/// use std::cmp::Ordering;
378///
379/// assert_eq!(1.cmp(&2), Ordering::Less);
380///
381/// assert_eq!(1.cmp(&1), Ordering::Equal);
382///
383/// assert_eq!(2.cmp(&1), Ordering::Greater);
384/// ```
385#[derive(Copy, Debug, Hash)]
386#[derive_const(Clone, Eq, PartialOrd, Ord, PartialEq)]
387#[stable(feature = "rust1", since = "1.0.0")]
388// This is a lang item only so that `BinOp::Cmp` in MIR can return it.
389// It has no special behavior, but does require that the three variants
390// `Less`/`Equal`/`Greater` remain `-1_i8`/`0_i8`/`+1_i8` respectively.
391#[lang = "Ordering"]
392#[repr(i8)]
393pub enum Ordering {
394    /// An ordering where a compared value is less than another.
395    #[stable(feature = "rust1", since = "1.0.0")]
396    Less = -1,
397    /// An ordering where a compared value is equal to another.
398    #[stable(feature = "rust1", since = "1.0.0")]
399    Equal = 0,
400    /// An ordering where a compared value is greater than another.
401    #[stable(feature = "rust1", since = "1.0.0")]
402    Greater = 1,
403}
404
405impl Ordering {
406    #[inline]
407    const fn as_raw(self) -> i8 {
408        // FIXME(const-hack): just use `PartialOrd` against `Equal` once that's const
409        crate::intrinsics::discriminant_value(&self)
410    }
411
412    /// Returns `true` if the ordering is the `Equal` variant.
413    ///
414    /// # Examples
415    ///
416    /// ```
417    /// use std::cmp::Ordering;
418    ///
419    /// assert_eq!(Ordering::Less.is_eq(), false);
420    /// assert_eq!(Ordering::Equal.is_eq(), true);
421    /// assert_eq!(Ordering::Greater.is_eq(), false);
422    /// ```
423    #[inline]
424    #[must_use]
425    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
426    #[stable(feature = "ordering_helpers", since = "1.53.0")]
427    pub const fn is_eq(self) -> bool {
428        // All the `is_*` methods are implemented as comparisons against zero
429        // to follow how clang's libcxx implements their equivalents in
430        // <https://github.com/llvm/llvm-project/blob/60486292b79885b7800b082754153202bef5b1f0/libcxx/include/__compare/is_eq.h#L23-L28>
431
432        self.as_raw() == 0
433    }
434
435    /// Returns `true` if the ordering is not the `Equal` variant.
436    ///
437    /// # Examples
438    ///
439    /// ```
440    /// use std::cmp::Ordering;
441    ///
442    /// assert_eq!(Ordering::Less.is_ne(), true);
443    /// assert_eq!(Ordering::Equal.is_ne(), false);
444    /// assert_eq!(Ordering::Greater.is_ne(), true);
445    /// ```
446    #[inline]
447    #[must_use]
448    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
449    #[stable(feature = "ordering_helpers", since = "1.53.0")]
450    pub const fn is_ne(self) -> bool {
451        self.as_raw() != 0
452    }
453
454    /// Returns `true` if the ordering is the `Less` variant.
455    ///
456    /// # Examples
457    ///
458    /// ```
459    /// use std::cmp::Ordering;
460    ///
461    /// assert_eq!(Ordering::Less.is_lt(), true);
462    /// assert_eq!(Ordering::Equal.is_lt(), false);
463    /// assert_eq!(Ordering::Greater.is_lt(), false);
464    /// ```
465    #[inline]
466    #[must_use]
467    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
468    #[stable(feature = "ordering_helpers", since = "1.53.0")]
469    pub const fn is_lt(self) -> bool {
470        self.as_raw() < 0
471    }
472
473    /// Returns `true` if the ordering is the `Greater` variant.
474    ///
475    /// # Examples
476    ///
477    /// ```
478    /// use std::cmp::Ordering;
479    ///
480    /// assert_eq!(Ordering::Less.is_gt(), false);
481    /// assert_eq!(Ordering::Equal.is_gt(), false);
482    /// assert_eq!(Ordering::Greater.is_gt(), true);
483    /// ```
484    #[inline]
485    #[must_use]
486    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
487    #[stable(feature = "ordering_helpers", since = "1.53.0")]
488    pub const fn is_gt(self) -> bool {
489        self.as_raw() > 0
490    }
491
492    /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
493    ///
494    /// # Examples
495    ///
496    /// ```
497    /// use std::cmp::Ordering;
498    ///
499    /// assert_eq!(Ordering::Less.is_le(), true);
500    /// assert_eq!(Ordering::Equal.is_le(), true);
501    /// assert_eq!(Ordering::Greater.is_le(), false);
502    /// ```
503    #[inline]
504    #[must_use]
505    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
506    #[stable(feature = "ordering_helpers", since = "1.53.0")]
507    pub const fn is_le(self) -> bool {
508        self.as_raw() <= 0
509    }
510
511    /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
512    ///
513    /// # Examples
514    ///
515    /// ```
516    /// use std::cmp::Ordering;
517    ///
518    /// assert_eq!(Ordering::Less.is_ge(), false);
519    /// assert_eq!(Ordering::Equal.is_ge(), true);
520    /// assert_eq!(Ordering::Greater.is_ge(), true);
521    /// ```
522    #[inline]
523    #[must_use]
524    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
525    #[stable(feature = "ordering_helpers", since = "1.53.0")]
526    pub const fn is_ge(self) -> bool {
527        self.as_raw() >= 0
528    }
529
530    /// Reverses the `Ordering`.
531    ///
532    /// * `Less` becomes `Greater`.
533    /// * `Greater` becomes `Less`.
534    /// * `Equal` becomes `Equal`.
535    ///
536    /// # Examples
537    ///
538    /// Basic behavior:
539    ///
540    /// ```
541    /// use std::cmp::Ordering;
542    ///
543    /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
544    /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
545    /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
546    /// ```
547    ///
548    /// This method can be used to reverse a comparison:
549    ///
550    /// ```
551    /// let data: &mut [_] = &mut [2, 10, 5, 8];
552    ///
553    /// // sort the array from largest to smallest.
554    /// data.sort_by(|a, b| a.cmp(b).reverse());
555    ///
556    /// let b: &mut [_] = &mut [10, 8, 5, 2];
557    /// assert!(data == b);
558    /// ```
559    #[inline]
560    #[must_use]
561    #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
562    #[stable(feature = "rust1", since = "1.0.0")]
563    pub const fn reverse(self) -> Ordering {
564        match self {
565            Less => Greater,
566            Equal => Equal,
567            Greater => Less,
568        }
569    }
570
571    /// Chains two orderings.
572    ///
573    /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
574    ///
575    /// # Examples
576    ///
577    /// ```
578    /// use std::cmp::Ordering;
579    ///
580    /// let result = Ordering::Equal.then(Ordering::Less);
581    /// assert_eq!(result, Ordering::Less);
582    ///
583    /// let result = Ordering::Less.then(Ordering::Equal);
584    /// assert_eq!(result, Ordering::Less);
585    ///
586    /// let result = Ordering::Less.then(Ordering::Greater);
587    /// assert_eq!(result, Ordering::Less);
588    ///
589    /// let result = Ordering::Equal.then(Ordering::Equal);
590    /// assert_eq!(result, Ordering::Equal);
591    ///
592    /// let x: (i64, i64, i64) = (1, 2, 7);
593    /// let y: (i64, i64, i64) = (1, 5, 3);
594    /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
595    ///
596    /// assert_eq!(result, Ordering::Less);
597    /// ```
598    #[inline]
599    #[must_use]
600    #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
601    #[stable(feature = "ordering_chaining", since = "1.17.0")]
602    pub const fn then(self, other: Ordering) -> Ordering {
603        match self {
604            Equal => other,
605            _ => self,
606        }
607    }
608
609    /// Chains the ordering with the given function.
610    ///
611    /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
612    /// the result.
613    ///
614    /// # Examples
615    ///
616    /// ```
617    /// use std::cmp::Ordering;
618    ///
619    /// let result = Ordering::Equal.then_with(|| Ordering::Less);
620    /// assert_eq!(result, Ordering::Less);
621    ///
622    /// let result = Ordering::Less.then_with(|| Ordering::Equal);
623    /// assert_eq!(result, Ordering::Less);
624    ///
625    /// let result = Ordering::Less.then_with(|| Ordering::Greater);
626    /// assert_eq!(result, Ordering::Less);
627    ///
628    /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
629    /// assert_eq!(result, Ordering::Equal);
630    ///
631    /// let x: (i64, i64, i64) = (1, 2, 7);
632    /// let y: (i64, i64, i64) = (1, 5, 3);
633    /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
634    ///
635    /// assert_eq!(result, Ordering::Less);
636    /// ```
637    #[inline]
638    #[must_use]
639    #[stable(feature = "ordering_chaining", since = "1.17.0")]
640    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
641    pub const fn then_with<F>(self, f: F) -> Ordering
642    where
643        F: [const] FnOnce() -> Ordering + [const] Destruct,
644    {
645        match self {
646            Equal => f(),
647            _ => self,
648        }
649    }
650}
651
652/// A helper struct for reverse ordering.
653///
654/// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
655/// can be used to reverse order a part of a key.
656///
657/// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
658///
659/// # Examples
660///
661/// ```
662/// use std::cmp::Reverse;
663///
664/// let mut v = vec![1, 2, 3, 4, 5, 6];
665/// v.sort_by_key(|&num| (num > 3, Reverse(num)));
666/// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
667/// ```
668#[derive(Copy, Debug, Hash)]
669#[derive_const(PartialEq, Eq, Default)]
670#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
671#[repr(transparent)]
672pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
673
674#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
675#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
676impl<T: [const] PartialOrd> const PartialOrd for Reverse<T> {
677    #[inline]
678    fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
679        other.0.partial_cmp(&self.0)
680    }
681
682    #[inline]
683    fn lt(&self, other: &Self) -> bool {
684        other.0 < self.0
685    }
686    #[inline]
687    fn le(&self, other: &Self) -> bool {
688        other.0 <= self.0
689    }
690    #[inline]
691    fn gt(&self, other: &Self) -> bool {
692        other.0 > self.0
693    }
694    #[inline]
695    fn ge(&self, other: &Self) -> bool {
696        other.0 >= self.0
697    }
698}
699
700#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
701#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
702impl<T: [const] Ord> const Ord for Reverse<T> {
703    #[inline]
704    fn cmp(&self, other: &Reverse<T>) -> Ordering {
705        other.0.cmp(&self.0)
706    }
707}
708
709#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
710impl<T: Clone> Clone for Reverse<T> {
711    #[inline]
712    fn clone(&self) -> Reverse<T> {
713        Reverse(self.0.clone())
714    }
715
716    #[inline]
717    fn clone_from(&mut self, source: &Self) {
718        self.0.clone_from(&source.0)
719    }
720}
721
722/// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
723///
724/// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure `max`,
725/// `min`, and `clamp` are consistent with `cmp`:
726///
727/// - `partial_cmp(a, b) == Some(cmp(a, b))`.
728/// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
729/// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
730/// - For `a.clamp(min, max)`, see the [method docs](#method.clamp) (ensured by the default
731///   implementation).
732///
733/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
734/// specified, but users of the trait must ensure that such logic errors do *not* result in
735/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
736/// methods.
737///
738/// ## Corollaries
739///
740/// From the above and the requirements of `PartialOrd`, it follows that for all `a`, `b` and `c`:
741///
742/// - exactly one of `a < b`, `a == b` or `a > b` is true; and
743/// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and
744///   `>`.
745///
746/// Mathematically speaking, the `<` operator defines a strict [weak order]. In cases where `==`
747/// conforms to mathematical equality, it also defines a strict [total order].
748///
749/// [weak order]: https://en.wikipedia.org/wiki/Weak_ordering
750/// [total order]: https://en.wikipedia.org/wiki/Total_order
751///
752/// ## Derivable
753///
754/// This trait can be used with `#[derive]`.
755///
756/// When `derive`d on structs, it will produce a
757/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the
758/// top-to-bottom declaration order of the struct's members.
759///
760/// When `derive`d on enums, variants are ordered primarily by their discriminants. Secondarily,
761/// they are ordered by their fields. By default, the discriminant is smallest for variants at the
762/// top, and largest for variants at the bottom. Here's an example:
763///
764/// ```
765/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
766/// enum E {
767///     Top,
768///     Bottom,
769/// }
770///
771/// assert!(E::Top < E::Bottom);
772/// ```
773///
774/// However, manually setting the discriminants can override this default behavior:
775///
776/// ```
777/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
778/// enum E {
779///     Top = 2,
780///     Bottom = 1,
781/// }
782///
783/// assert!(E::Bottom < E::Top);
784/// ```
785///
786/// ## Lexicographical comparison
787///
788/// Lexicographical comparison is an operation with the following properties:
789///  - Two sequences are compared element by element.
790///  - The first mismatching element defines which sequence is lexicographically less or greater
791///    than the other.
792///  - If one sequence is a prefix of another, the shorter sequence is lexicographically less than
793///    the other.
794///  - If two sequences have equivalent elements and are of the same length, then the sequences are
795///    lexicographically equal.
796///  - An empty sequence is lexicographically less than any non-empty sequence.
797///  - Two empty sequences are lexicographically equal.
798///
799/// ## How can I implement `Ord`?
800///
801/// `Ord` requires that the type also be [`PartialOrd`], [`PartialEq`], and [`Eq`].
802///
803/// Because `Ord` implies a stronger ordering relationship than [`PartialOrd`], and both `Ord` and
804/// [`PartialOrd`] must agree, you must choose how to implement `Ord` **first**. You can choose to
805/// derive it, or implement it manually. If you derive it, you should derive all four traits. If you
806/// implement it manually, you should manually implement all four traits, based on the
807/// implementation of `Ord`.
808///
809/// Here's an example where you want to define the `Character` comparison by `health` and
810/// `experience` only, disregarding the field `mana`:
811///
812/// ```
813/// use std::cmp::Ordering;
814///
815/// struct Character {
816///     health: u32,
817///     experience: u32,
818///     mana: f32,
819/// }
820///
821/// impl Ord for Character {
822///     fn cmp(&self, other: &Self) -> Ordering {
823///         self.experience
824///             .cmp(&other.experience)
825///             .then(self.health.cmp(&other.health))
826///     }
827/// }
828///
829/// impl PartialOrd for Character {
830///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
831///         Some(self.cmp(other))
832///     }
833/// }
834///
835/// impl PartialEq for Character {
836///     fn eq(&self, other: &Self) -> bool {
837///         self.health == other.health && self.experience == other.experience
838///     }
839/// }
840///
841/// impl Eq for Character {}
842/// ```
843///
844/// If all you need is to `slice::sort` a type by a field value, it can be simpler to use
845/// `slice::sort_by_key`.
846///
847/// ## Examples of incorrect `Ord` implementations
848///
849/// ```
850/// use std::cmp::Ordering;
851///
852/// #[derive(Debug)]
853/// struct Character {
854///     health: f32,
855/// }
856///
857/// impl Ord for Character {
858///     fn cmp(&self, other: &Self) -> std::cmp::Ordering {
859///         if self.health < other.health {
860///             Ordering::Less
861///         } else if self.health > other.health {
862///             Ordering::Greater
863///         } else {
864///             Ordering::Equal
865///         }
866///     }
867/// }
868///
869/// impl PartialOrd for Character {
870///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
871///         Some(self.cmp(other))
872///     }
873/// }
874///
875/// impl PartialEq for Character {
876///     fn eq(&self, other: &Self) -> bool {
877///         self.health == other.health
878///     }
879/// }
880///
881/// impl Eq for Character {}
882///
883/// let a = Character { health: 4.5 };
884/// let b = Character { health: f32::NAN };
885///
886/// // Mistake: floating-point values do not form a total order and using the built-in comparison
887/// // operands to implement `Ord` irregardless of that reality does not change it. Use
888/// // `f32::total_cmp` if you need a total order for floating-point values.
889///
890/// // Reflexivity requirement of `Ord` is not given.
891/// assert!(a == a);
892/// assert!(b != b);
893///
894/// // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be
895/// // true, not both or neither.
896/// assert_eq!((a < b) as u8 + (b < a) as u8, 0);
897/// ```
898///
899/// ```
900/// use std::cmp::Ordering;
901///
902/// #[derive(Debug)]
903/// struct Character {
904///     health: u32,
905///     experience: u32,
906/// }
907///
908/// impl PartialOrd for Character {
909///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
910///         Some(self.cmp(other))
911///     }
912/// }
913///
914/// impl Ord for Character {
915///     fn cmp(&self, other: &Self) -> std::cmp::Ordering {
916///         if self.health < 50 {
917///             self.health.cmp(&other.health)
918///         } else {
919///             self.experience.cmp(&other.experience)
920///         }
921///     }
922/// }
923///
924/// // For performance reasons implementing `PartialEq` this way is not the idiomatic way, but it
925/// // ensures consistent behavior between `PartialEq`, `PartialOrd` and `Ord` in this example.
926/// impl PartialEq for Character {
927///     fn eq(&self, other: &Self) -> bool {
928///         self.cmp(other) == Ordering::Equal
929///     }
930/// }
931///
932/// impl Eq for Character {}
933///
934/// let a = Character {
935///     health: 3,
936///     experience: 5,
937/// };
938/// let b = Character {
939///     health: 10,
940///     experience: 77,
941/// };
942/// let c = Character {
943///     health: 143,
944///     experience: 2,
945/// };
946///
947/// // Mistake: The implementation of `Ord` compares different fields depending on the value of
948/// // `self.health`, the resulting order is not total.
949///
950/// // Transitivity requirement of `Ord` is not given. If a is smaller than b and b is smaller than
951/// // c, by transitive property a must also be smaller than c.
952/// assert!(a < b && b < c && c < a);
953///
954/// // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be
955/// // true, not both or neither.
956/// assert_eq!((a < c) as u8 + (c < a) as u8, 2);
957/// ```
958///
959/// The documentation of [`PartialOrd`] contains further examples, for example it's wrong for
960/// [`PartialOrd`] and [`PartialEq`] to disagree.
961///
962/// [`cmp`]: Ord::cmp
963#[doc(alias = "<")]
964#[doc(alias = ">")]
965#[doc(alias = "<=")]
966#[doc(alias = ">=")]
967#[stable(feature = "rust1", since = "1.0.0")]
968#[rustc_diagnostic_item = "Ord"]
969#[const_trait]
970#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
971pub trait Ord: [const] Eq + [const] PartialOrd<Self> + PointeeSized {
972    /// This method returns an [`Ordering`] between `self` and `other`.
973    ///
974    /// By convention, `self.cmp(&other)` returns the ordering matching the expression
975    /// `self <operator> other` if true.
976    ///
977    /// # Examples
978    ///
979    /// ```
980    /// use std::cmp::Ordering;
981    ///
982    /// assert_eq!(5.cmp(&10), Ordering::Less);
983    /// assert_eq!(10.cmp(&5), Ordering::Greater);
984    /// assert_eq!(5.cmp(&5), Ordering::Equal);
985    /// ```
986    #[must_use]
987    #[stable(feature = "rust1", since = "1.0.0")]
988    #[rustc_diagnostic_item = "ord_cmp_method"]
989    fn cmp(&self, other: &Self) -> Ordering;
990
991    /// Compares and returns the maximum of two values.
992    ///
993    /// Returns the second argument if the comparison determines them to be equal.
994    ///
995    /// # Examples
996    ///
997    /// ```
998    /// assert_eq!(1.max(2), 2);
999    /// assert_eq!(2.max(2), 2);
1000    /// ```
1001    /// ```
1002    /// use std::cmp::Ordering;
1003    ///
1004    /// #[derive(Eq)]
1005    /// struct Equal(&'static str);
1006    ///
1007    /// impl PartialEq for Equal {
1008    ///     fn eq(&self, other: &Self) -> bool { true }
1009    /// }
1010    /// impl PartialOrd for Equal {
1011    ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1012    /// }
1013    /// impl Ord for Equal {
1014    ///     fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1015    /// }
1016    ///
1017    /// assert_eq!(Equal("self").max(Equal("other")).0, "other");
1018    /// ```
1019    #[stable(feature = "ord_max_min", since = "1.21.0")]
1020    #[inline]
1021    #[must_use]
1022    #[rustc_diagnostic_item = "cmp_ord_max"]
1023    fn max(self, other: Self) -> Self
1024    where
1025        Self: Sized + [const] Destruct,
1026    {
1027        if other < self { self } else { other }
1028    }
1029
1030    /// Compares and returns the minimum of two values.
1031    ///
1032    /// Returns the first argument if the comparison determines them to be equal.
1033    ///
1034    /// # Examples
1035    ///
1036    /// ```
1037    /// assert_eq!(1.min(2), 1);
1038    /// assert_eq!(2.min(2), 2);
1039    /// ```
1040    /// ```
1041    /// use std::cmp::Ordering;
1042    ///
1043    /// #[derive(Eq)]
1044    /// struct Equal(&'static str);
1045    ///
1046    /// impl PartialEq for Equal {
1047    ///     fn eq(&self, other: &Self) -> bool { true }
1048    /// }
1049    /// impl PartialOrd for Equal {
1050    ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1051    /// }
1052    /// impl Ord for Equal {
1053    ///     fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1054    /// }
1055    ///
1056    /// assert_eq!(Equal("self").min(Equal("other")).0, "self");
1057    /// ```
1058    #[stable(feature = "ord_max_min", since = "1.21.0")]
1059    #[inline]
1060    #[must_use]
1061    #[rustc_diagnostic_item = "cmp_ord_min"]
1062    fn min(self, other: Self) -> Self
1063    where
1064        Self: Sized + [const] Destruct,
1065    {
1066        if other < self { other } else { self }
1067    }
1068
1069    /// Restrict a value to a certain interval.
1070    ///
1071    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1072    /// less than `min`. Otherwise this returns `self`.
1073    ///
1074    /// # Panics
1075    ///
1076    /// Panics if `min > max`.
1077    ///
1078    /// # Examples
1079    ///
1080    /// ```
1081    /// assert_eq!((-3).clamp(-2, 1), -2);
1082    /// assert_eq!(0.clamp(-2, 1), 0);
1083    /// assert_eq!(2.clamp(-2, 1), 1);
1084    /// ```
1085    #[must_use]
1086    #[inline]
1087    #[stable(feature = "clamp", since = "1.50.0")]
1088    fn clamp(self, min: Self, max: Self) -> Self
1089    where
1090        Self: Sized + [const] Destruct,
1091    {
1092        assert!(min <= max);
1093        if self < min {
1094            min
1095        } else if self > max {
1096            max
1097        } else {
1098            self
1099        }
1100    }
1101}
1102
1103/// Derive macro generating an impl of the trait [`Ord`].
1104/// The behavior of this macro is described in detail [here](Ord#derivable).
1105#[rustc_builtin_macro]
1106#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1107#[allow_internal_unstable(core_intrinsics)]
1108pub macro Ord($item:item) {
1109    /* compiler built-in */
1110}
1111
1112/// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
1113///
1114/// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using the `<`, `<=`, `>`, and
1115/// `>=` operators, respectively.
1116///
1117/// This trait should **only** contain the comparison logic for a type **if one plans on only
1118/// implementing `PartialOrd` but not [`Ord`]**. Otherwise the comparison logic should be in [`Ord`]
1119/// and this trait implemented with `Some(self.cmp(other))`.
1120///
1121/// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
1122/// The following conditions must hold:
1123///
1124/// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
1125/// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
1126/// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
1127/// 4. `a <= b` if and only if `a < b || a == b`
1128/// 5. `a >= b` if and only if `a > b || a == b`
1129/// 6. `a != b` if and only if `!(a == b)`.
1130///
1131/// Conditions 2–5 above are ensured by the default implementation. Condition 6 is already ensured
1132/// by [`PartialEq`].
1133///
1134/// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
1135/// `partial_cmp` (see the documentation of that trait for the exact requirements). It's easy to
1136/// accidentally make them disagree by deriving some of the traits and manually implementing others.
1137///
1138/// The comparison relations must satisfy the following conditions (for all `a`, `b`, `c` of type
1139/// `A`, `B`, `C`):
1140///
1141/// - **Transitivity**: if `A: PartialOrd<B>` and `B: PartialOrd<C>` and `A: PartialOrd<C>`, then `a
1142///   < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. This must also
1143///   work for longer chains, such as when `A: PartialOrd<B>`, `B: PartialOrd<C>`, `C:
1144///   PartialOrd<D>`, and `A: PartialOrd<D>` all exist.
1145/// - **Duality**: if `A: PartialOrd<B>` and `B: PartialOrd<A>`, then `a < b` if and only if `b >
1146///   a`.
1147///
1148/// Note that the `B: PartialOrd<A>` (dual) and `A: PartialOrd<C>` (transitive) impls are not forced
1149/// to exist, but these requirements apply whenever they do exist.
1150///
1151/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
1152/// specified, but users of the trait must ensure that such logic errors do *not* result in
1153/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
1154/// methods.
1155///
1156/// ## Cross-crate considerations
1157///
1158/// Upholding the requirements stated above can become tricky when one crate implements `PartialOrd`
1159/// for a type of another crate (i.e., to allow comparing one of its own types with a type from the
1160/// standard library). The recommendation is to never implement this trait for a foreign type. In
1161/// other words, such a crate should do `impl PartialOrd<ForeignType> for LocalType`, but it should
1162/// *not* do `impl PartialOrd<LocalType> for ForeignType`.
1163///
1164/// This avoids the problem of transitive chains that criss-cross crate boundaries: for all local
1165/// types `T`, you may assume that no other crate will add `impl`s that allow comparing `T < U`. In
1166/// other words, if other crates add `impl`s that allow building longer transitive chains `U1 < ...
1167/// < T < V1 < ...`, then all the types that appear to the right of `T` must be types that the crate
1168/// defining `T` already knows about. This rules out transitive chains where downstream crates can
1169/// add new `impl`s that "stitch together" comparisons of foreign types in ways that violate
1170/// transitivity.
1171///
1172/// Not having such foreign `impl`s also avoids forward compatibility issues where one crate adding
1173/// more `PartialOrd` implementations can cause build failures in downstream crates.
1174///
1175/// ## Corollaries
1176///
1177/// The following corollaries follow from the above requirements:
1178///
1179/// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
1180/// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
1181/// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
1182///
1183/// ## Strict and non-strict partial orders
1184///
1185/// The `<` and `>` operators behave according to a *strict* partial order. However, `<=` and `>=`
1186/// do **not** behave according to a *non-strict* partial order. That is because mathematically, a
1187/// non-strict partial order would require reflexivity, i.e. `a <= a` would need to be true for
1188/// every `a`. This isn't always the case for types that implement `PartialOrd`, for example:
1189///
1190/// ```
1191/// let a = f64::sqrt(-1.0);
1192/// assert_eq!(a <= a, false);
1193/// ```
1194///
1195/// ## Derivable
1196///
1197/// This trait can be used with `#[derive]`.
1198///
1199/// When `derive`d on structs, it will produce a
1200/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the
1201/// top-to-bottom declaration order of the struct's members.
1202///
1203/// When `derive`d on enums, variants are primarily ordered by their discriminants. Secondarily,
1204/// they are ordered by their fields. By default, the discriminant is smallest for variants at the
1205/// top, and largest for variants at the bottom. Here's an example:
1206///
1207/// ```
1208/// #[derive(PartialEq, PartialOrd)]
1209/// enum E {
1210///     Top,
1211///     Bottom,
1212/// }
1213///
1214/// assert!(E::Top < E::Bottom);
1215/// ```
1216///
1217/// However, manually setting the discriminants can override this default behavior:
1218///
1219/// ```
1220/// #[derive(PartialEq, PartialOrd)]
1221/// enum E {
1222///     Top = 2,
1223///     Bottom = 1,
1224/// }
1225///
1226/// assert!(E::Bottom < E::Top);
1227/// ```
1228///
1229/// ## How can I implement `PartialOrd`?
1230///
1231/// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
1232/// generated from default implementations.
1233///
1234/// However it remains possible to implement the others separately for types which do not have a
1235/// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 == false`
1236/// (cf. IEEE 754-2008 section 5.11).
1237///
1238/// `PartialOrd` requires your type to be [`PartialEq`].
1239///
1240/// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
1241///
1242/// ```
1243/// use std::cmp::Ordering;
1244///
1245/// struct Person {
1246///     id: u32,
1247///     name: String,
1248///     height: u32,
1249/// }
1250///
1251/// impl PartialOrd for Person {
1252///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1253///         Some(self.cmp(other))
1254///     }
1255/// }
1256///
1257/// impl Ord for Person {
1258///     fn cmp(&self, other: &Self) -> Ordering {
1259///         self.height.cmp(&other.height)
1260///     }
1261/// }
1262///
1263/// impl PartialEq for Person {
1264///     fn eq(&self, other: &Self) -> bool {
1265///         self.height == other.height
1266///     }
1267/// }
1268///
1269/// impl Eq for Person {}
1270/// ```
1271///
1272/// You may also find it useful to use [`partial_cmp`] on your type's fields. Here is an example of
1273/// `Person` types who have a floating-point `height` field that is the only field to be used for
1274/// sorting:
1275///
1276/// ```
1277/// use std::cmp::Ordering;
1278///
1279/// struct Person {
1280///     id: u32,
1281///     name: String,
1282///     height: f64,
1283/// }
1284///
1285/// impl PartialOrd for Person {
1286///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1287///         self.height.partial_cmp(&other.height)
1288///     }
1289/// }
1290///
1291/// impl PartialEq for Person {
1292///     fn eq(&self, other: &Self) -> bool {
1293///         self.height == other.height
1294///     }
1295/// }
1296/// ```
1297///
1298/// ## Examples of incorrect `PartialOrd` implementations
1299///
1300/// ```
1301/// use std::cmp::Ordering;
1302///
1303/// #[derive(PartialEq, Debug)]
1304/// struct Character {
1305///     health: u32,
1306///     experience: u32,
1307/// }
1308///
1309/// impl PartialOrd for Character {
1310///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1311///         Some(self.health.cmp(&other.health))
1312///     }
1313/// }
1314///
1315/// let a = Character {
1316///     health: 10,
1317///     experience: 5,
1318/// };
1319/// let b = Character {
1320///     health: 10,
1321///     experience: 77,
1322/// };
1323///
1324/// // Mistake: `PartialEq` and `PartialOrd` disagree with each other.
1325///
1326/// assert_eq!(a.partial_cmp(&b).unwrap(), Ordering::Equal); // a == b according to `PartialOrd`.
1327/// assert_ne!(a, b); // a != b according to `PartialEq`.
1328/// ```
1329///
1330/// # Examples
1331///
1332/// ```
1333/// let x: u32 = 0;
1334/// let y: u32 = 1;
1335///
1336/// assert_eq!(x < y, true);
1337/// assert_eq!(x.lt(&y), true);
1338/// ```
1339///
1340/// [`partial_cmp`]: PartialOrd::partial_cmp
1341/// [`cmp`]: Ord::cmp
1342#[lang = "partial_ord"]
1343#[stable(feature = "rust1", since = "1.0.0")]
1344#[doc(alias = ">")]
1345#[doc(alias = "<")]
1346#[doc(alias = "<=")]
1347#[doc(alias = ">=")]
1348#[rustc_on_unimplemented(
1349    message = "can't compare `{Self}` with `{Rhs}`",
1350    label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1351    append_const_msg
1352)]
1353#[rustc_diagnostic_item = "PartialOrd"]
1354#[allow(multiple_supertrait_upcastable)] // FIXME(sized_hierarchy): remove this
1355#[const_trait]
1356#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1357pub trait PartialOrd<Rhs: PointeeSized = Self>: PartialEq<Rhs> + PointeeSized {
1358    /// This method returns an ordering between `self` and `other` values if one exists.
1359    ///
1360    /// # Examples
1361    ///
1362    /// ```
1363    /// use std::cmp::Ordering;
1364    ///
1365    /// let result = 1.0.partial_cmp(&2.0);
1366    /// assert_eq!(result, Some(Ordering::Less));
1367    ///
1368    /// let result = 1.0.partial_cmp(&1.0);
1369    /// assert_eq!(result, Some(Ordering::Equal));
1370    ///
1371    /// let result = 2.0.partial_cmp(&1.0);
1372    /// assert_eq!(result, Some(Ordering::Greater));
1373    /// ```
1374    ///
1375    /// When comparison is impossible:
1376    ///
1377    /// ```
1378    /// let result = f64::NAN.partial_cmp(&1.0);
1379    /// assert_eq!(result, None);
1380    /// ```
1381    #[must_use]
1382    #[stable(feature = "rust1", since = "1.0.0")]
1383    #[rustc_diagnostic_item = "cmp_partialord_cmp"]
1384    fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1385
1386    /// Tests less than (for `self` and `other`) and is used by the `<` operator.
1387    ///
1388    /// # Examples
1389    ///
1390    /// ```
1391    /// assert_eq!(1.0 < 1.0, false);
1392    /// assert_eq!(1.0 < 2.0, true);
1393    /// assert_eq!(2.0 < 1.0, false);
1394    /// ```
1395    #[inline]
1396    #[must_use]
1397    #[stable(feature = "rust1", since = "1.0.0")]
1398    #[rustc_diagnostic_item = "cmp_partialord_lt"]
1399    fn lt(&self, other: &Rhs) -> bool {
1400        self.partial_cmp(other).is_some_and(Ordering::is_lt)
1401    }
1402
1403    /// Tests less than or equal to (for `self` and `other`) and is used by the
1404    /// `<=` operator.
1405    ///
1406    /// # Examples
1407    ///
1408    /// ```
1409    /// assert_eq!(1.0 <= 1.0, true);
1410    /// assert_eq!(1.0 <= 2.0, true);
1411    /// assert_eq!(2.0 <= 1.0, false);
1412    /// ```
1413    #[inline]
1414    #[must_use]
1415    #[stable(feature = "rust1", since = "1.0.0")]
1416    #[rustc_diagnostic_item = "cmp_partialord_le"]
1417    fn le(&self, other: &Rhs) -> bool {
1418        self.partial_cmp(other).is_some_and(Ordering::is_le)
1419    }
1420
1421    /// Tests greater than (for `self` and `other`) and is used by the `>`
1422    /// operator.
1423    ///
1424    /// # Examples
1425    ///
1426    /// ```
1427    /// assert_eq!(1.0 > 1.0, false);
1428    /// assert_eq!(1.0 > 2.0, false);
1429    /// assert_eq!(2.0 > 1.0, true);
1430    /// ```
1431    #[inline]
1432    #[must_use]
1433    #[stable(feature = "rust1", since = "1.0.0")]
1434    #[rustc_diagnostic_item = "cmp_partialord_gt"]
1435    fn gt(&self, other: &Rhs) -> bool {
1436        self.partial_cmp(other).is_some_and(Ordering::is_gt)
1437    }
1438
1439    /// Tests greater than or equal to (for `self` and `other`) and is used by
1440    /// the `>=` operator.
1441    ///
1442    /// # Examples
1443    ///
1444    /// ```
1445    /// assert_eq!(1.0 >= 1.0, true);
1446    /// assert_eq!(1.0 >= 2.0, false);
1447    /// assert_eq!(2.0 >= 1.0, true);
1448    /// ```
1449    #[inline]
1450    #[must_use]
1451    #[stable(feature = "rust1", since = "1.0.0")]
1452    #[rustc_diagnostic_item = "cmp_partialord_ge"]
1453    fn ge(&self, other: &Rhs) -> bool {
1454        self.partial_cmp(other).is_some_and(Ordering::is_ge)
1455    }
1456
1457    /// If `self == other`, returns `ControlFlow::Continue(())`.
1458    /// Otherwise, returns `ControlFlow::Break(self < other)`.
1459    ///
1460    /// This is useful for chaining together calls when implementing a lexical
1461    /// `PartialOrd::lt`, as it allows types (like primitives) which can cheaply
1462    /// check `==` and `<` separately to do rather than needing to calculate
1463    /// (then optimize out) the three-way `Ordering` result.
1464    #[inline]
1465    // Added to improve the behaviour of tuples; not necessarily stabilization-track.
1466    #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1467    #[doc(hidden)]
1468    fn __chaining_lt(&self, other: &Rhs) -> ControlFlow<bool> {
1469        default_chaining_impl(self, other, Ordering::is_lt)
1470    }
1471
1472    /// Same as `__chaining_lt`, but for `<=` instead of `<`.
1473    #[inline]
1474    #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1475    #[doc(hidden)]
1476    fn __chaining_le(&self, other: &Rhs) -> ControlFlow<bool> {
1477        default_chaining_impl(self, other, Ordering::is_le)
1478    }
1479
1480    /// Same as `__chaining_lt`, but for `>` instead of `<`.
1481    #[inline]
1482    #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1483    #[doc(hidden)]
1484    fn __chaining_gt(&self, other: &Rhs) -> ControlFlow<bool> {
1485        default_chaining_impl(self, other, Ordering::is_gt)
1486    }
1487
1488    /// Same as `__chaining_lt`, but for `>=` instead of `<`.
1489    #[inline]
1490    #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1491    #[doc(hidden)]
1492    fn __chaining_ge(&self, other: &Rhs) -> ControlFlow<bool> {
1493        default_chaining_impl(self, other, Ordering::is_ge)
1494    }
1495}
1496
1497#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1498const fn default_chaining_impl<T, U>(
1499    lhs: &T,
1500    rhs: &U,
1501    p: impl [const] FnOnce(Ordering) -> bool + [const] Destruct,
1502) -> ControlFlow<bool>
1503where
1504    T: [const] PartialOrd<U> + PointeeSized,
1505    U: PointeeSized,
1506{
1507    // It's important that this only call `partial_cmp` once, not call `eq` then
1508    // one of the relational operators.  We don't want to `bcmp`-then-`memcp` a
1509    // `String`, for example, or similarly for other data structures (#108157).
1510    match <T as PartialOrd<U>>::partial_cmp(lhs, rhs) {
1511        Some(Equal) => ControlFlow::Continue(()),
1512        Some(c) => ControlFlow::Break(p(c)),
1513        None => ControlFlow::Break(false),
1514    }
1515}
1516
1517/// Derive macro generating an impl of the trait [`PartialOrd`].
1518/// The behavior of this macro is described in detail [here](PartialOrd#derivable).
1519#[rustc_builtin_macro]
1520#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1521#[allow_internal_unstable(core_intrinsics)]
1522pub macro PartialOrd($item:item) {
1523    /* compiler built-in */
1524}
1525
1526/// Compares and returns the minimum of two values.
1527///
1528/// Returns the first argument if the comparison determines them to be equal.
1529///
1530/// Internally uses an alias to [`Ord::min`].
1531///
1532/// # Examples
1533///
1534/// ```
1535/// use std::cmp;
1536///
1537/// assert_eq!(cmp::min(1, 2), 1);
1538/// assert_eq!(cmp::min(2, 2), 2);
1539/// ```
1540/// ```
1541/// use std::cmp::{self, Ordering};
1542///
1543/// #[derive(Eq)]
1544/// struct Equal(&'static str);
1545///
1546/// impl PartialEq for Equal {
1547///     fn eq(&self, other: &Self) -> bool { true }
1548/// }
1549/// impl PartialOrd for Equal {
1550///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1551/// }
1552/// impl Ord for Equal {
1553///     fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1554/// }
1555///
1556/// assert_eq!(cmp::min(Equal("v1"), Equal("v2")).0, "v1");
1557/// ```
1558#[inline]
1559#[must_use]
1560#[stable(feature = "rust1", since = "1.0.0")]
1561#[rustc_diagnostic_item = "cmp_min"]
1562#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1563pub const fn min<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1564    v1.min(v2)
1565}
1566
1567/// Returns the minimum of two values with respect to the specified comparison function.
1568///
1569/// Returns the first argument if the comparison determines them to be equal.
1570///
1571/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1572/// always passed as the first argument and `v2` as the second.
1573///
1574/// # Examples
1575///
1576/// ```
1577/// use std::cmp;
1578///
1579/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1580///
1581/// let result = cmp::min_by(2, -1, abs_cmp);
1582/// assert_eq!(result, -1);
1583///
1584/// let result = cmp::min_by(2, -3, abs_cmp);
1585/// assert_eq!(result, 2);
1586///
1587/// let result = cmp::min_by(1, -1, abs_cmp);
1588/// assert_eq!(result, 1);
1589/// ```
1590#[inline]
1591#[must_use]
1592#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1593#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1594pub const fn min_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1595    v1: T,
1596    v2: T,
1597    compare: F,
1598) -> T {
1599    if compare(&v1, &v2).is_le() { v1 } else { v2 }
1600}
1601
1602/// Returns the element that gives the minimum value from the specified function.
1603///
1604/// Returns the first argument if the comparison determines them to be equal.
1605///
1606/// # Examples
1607///
1608/// ```
1609/// use std::cmp;
1610///
1611/// let result = cmp::min_by_key(2, -1, |x: &i32| x.abs());
1612/// assert_eq!(result, -1);
1613///
1614/// let result = cmp::min_by_key(2, -3, |x: &i32| x.abs());
1615/// assert_eq!(result, 2);
1616///
1617/// let result = cmp::min_by_key(1, -1, |x: &i32| x.abs());
1618/// assert_eq!(result, 1);
1619/// ```
1620#[inline]
1621#[must_use]
1622#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1623#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1624pub const fn min_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1625where
1626    T: [const] Destruct,
1627    F: [const] FnMut(&T) -> K + [const] Destruct,
1628    K: [const] Ord + [const] Destruct,
1629{
1630    if f(&v2) < f(&v1) { v2 } else { v1 }
1631}
1632
1633/// Compares and returns the maximum of two values.
1634///
1635/// Returns the second argument if the comparison determines them to be equal.
1636///
1637/// Internally uses an alias to [`Ord::max`].
1638///
1639/// # Examples
1640///
1641/// ```
1642/// use std::cmp;
1643///
1644/// assert_eq!(cmp::max(1, 2), 2);
1645/// assert_eq!(cmp::max(2, 2), 2);
1646/// ```
1647/// ```
1648/// use std::cmp::{self, Ordering};
1649///
1650/// #[derive(Eq)]
1651/// struct Equal(&'static str);
1652///
1653/// impl PartialEq for Equal {
1654///     fn eq(&self, other: &Self) -> bool { true }
1655/// }
1656/// impl PartialOrd for Equal {
1657///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1658/// }
1659/// impl Ord for Equal {
1660///     fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1661/// }
1662///
1663/// assert_eq!(cmp::max(Equal("v1"), Equal("v2")).0, "v2");
1664/// ```
1665#[inline]
1666#[must_use]
1667#[stable(feature = "rust1", since = "1.0.0")]
1668#[rustc_diagnostic_item = "cmp_max"]
1669#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1670pub const fn max<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1671    v1.max(v2)
1672}
1673
1674/// Returns the maximum of two values with respect to the specified comparison function.
1675///
1676/// Returns the second argument if the comparison determines them to be equal.
1677///
1678/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1679/// always passed as the first argument and `v2` as the second.
1680///
1681/// # Examples
1682///
1683/// ```
1684/// use std::cmp;
1685///
1686/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1687///
1688/// let result = cmp::max_by(3, -2, abs_cmp) ;
1689/// assert_eq!(result, 3);
1690///
1691/// let result = cmp::max_by(1, -2, abs_cmp);
1692/// assert_eq!(result, -2);
1693///
1694/// let result = cmp::max_by(1, -1, abs_cmp);
1695/// assert_eq!(result, -1);
1696/// ```
1697#[inline]
1698#[must_use]
1699#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1700#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1701pub const fn max_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1702    v1: T,
1703    v2: T,
1704    compare: F,
1705) -> T {
1706    if compare(&v1, &v2).is_gt() { v1 } else { v2 }
1707}
1708
1709/// Returns the element that gives the maximum value from the specified function.
1710///
1711/// Returns the second argument if the comparison determines them to be equal.
1712///
1713/// # Examples
1714///
1715/// ```
1716/// use std::cmp;
1717///
1718/// let result = cmp::max_by_key(3, -2, |x: &i32| x.abs());
1719/// assert_eq!(result, 3);
1720///
1721/// let result = cmp::max_by_key(1, -2, |x: &i32| x.abs());
1722/// assert_eq!(result, -2);
1723///
1724/// let result = cmp::max_by_key(1, -1, |x: &i32| x.abs());
1725/// assert_eq!(result, -1);
1726/// ```
1727#[inline]
1728#[must_use]
1729#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1730#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1731pub const fn max_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1732where
1733    T: [const] Destruct,
1734    F: [const] FnMut(&T) -> K + [const] Destruct,
1735    K: [const] Ord + [const] Destruct,
1736{
1737    if f(&v2) < f(&v1) { v1 } else { v2 }
1738}
1739
1740/// Compares and sorts two values, returning minimum and maximum.
1741///
1742/// Returns `[v1, v2]` if the comparison determines them to be equal.
1743///
1744/// # Examples
1745///
1746/// ```
1747/// #![feature(cmp_minmax)]
1748/// use std::cmp;
1749///
1750/// assert_eq!(cmp::minmax(1, 2), [1, 2]);
1751/// assert_eq!(cmp::minmax(2, 1), [1, 2]);
1752///
1753/// // You can destructure the result using array patterns
1754/// let [min, max] = cmp::minmax(42, 17);
1755/// assert_eq!(min, 17);
1756/// assert_eq!(max, 42);
1757/// ```
1758/// ```
1759/// #![feature(cmp_minmax)]
1760/// use std::cmp::{self, Ordering};
1761///
1762/// #[derive(Eq)]
1763/// struct Equal(&'static str);
1764///
1765/// impl PartialEq for Equal {
1766///     fn eq(&self, other: &Self) -> bool { true }
1767/// }
1768/// impl PartialOrd for Equal {
1769///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1770/// }
1771/// impl Ord for Equal {
1772///     fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1773/// }
1774///
1775/// assert_eq!(cmp::minmax(Equal("v1"), Equal("v2")).map(|v| v.0), ["v1", "v2"]);
1776/// ```
1777#[inline]
1778#[must_use]
1779#[unstable(feature = "cmp_minmax", issue = "115939")]
1780#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1781pub const fn minmax<T>(v1: T, v2: T) -> [T; 2]
1782where
1783    T: [const] Ord,
1784{
1785    if v2 < v1 { [v2, v1] } else { [v1, v2] }
1786}
1787
1788/// Returns minimum and maximum values with respect to the specified comparison function.
1789///
1790/// Returns `[v1, v2]` if the comparison determines them to be equal.
1791///
1792/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1793/// always passed as the first argument and `v2` as the second.
1794///
1795/// # Examples
1796///
1797/// ```
1798/// #![feature(cmp_minmax)]
1799/// use std::cmp;
1800///
1801/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1802///
1803/// assert_eq!(cmp::minmax_by(-2, 1, abs_cmp), [1, -2]);
1804/// assert_eq!(cmp::minmax_by(-1, 2, abs_cmp), [-1, 2]);
1805/// assert_eq!(cmp::minmax_by(-2, 2, abs_cmp), [-2, 2]);
1806///
1807/// // You can destructure the result using array patterns
1808/// let [min, max] = cmp::minmax_by(-42, 17, abs_cmp);
1809/// assert_eq!(min, 17);
1810/// assert_eq!(max, -42);
1811/// ```
1812#[inline]
1813#[must_use]
1814#[unstable(feature = "cmp_minmax", issue = "115939")]
1815#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1816pub const fn minmax_by<T, F>(v1: T, v2: T, compare: F) -> [T; 2]
1817where
1818    F: [const] FnOnce(&T, &T) -> Ordering,
1819{
1820    if compare(&v1, &v2).is_le() { [v1, v2] } else { [v2, v1] }
1821}
1822
1823/// Returns minimum and maximum values with respect to the specified key function.
1824///
1825/// Returns `[v1, v2]` if the comparison determines them to be equal.
1826///
1827/// # Examples
1828///
1829/// ```
1830/// #![feature(cmp_minmax)]
1831/// use std::cmp;
1832///
1833/// assert_eq!(cmp::minmax_by_key(-2, 1, |x: &i32| x.abs()), [1, -2]);
1834/// assert_eq!(cmp::minmax_by_key(-2, 2, |x: &i32| x.abs()), [-2, 2]);
1835///
1836/// // You can destructure the result using array patterns
1837/// let [min, max] = cmp::minmax_by_key(-42, 17, |x: &i32| x.abs());
1838/// assert_eq!(min, 17);
1839/// assert_eq!(max, -42);
1840/// ```
1841#[inline]
1842#[must_use]
1843#[unstable(feature = "cmp_minmax", issue = "115939")]
1844#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1845pub const fn minmax_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> [T; 2]
1846where
1847    F: [const] FnMut(&T) -> K + [const] Destruct,
1848    K: [const] Ord + [const] Destruct,
1849{
1850    if f(&v2) < f(&v1) { [v2, v1] } else { [v1, v2] }
1851}
1852
1853// Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1854mod impls {
1855    use crate::cmp::Ordering::{self, Equal, Greater, Less};
1856    use crate::hint::unreachable_unchecked;
1857    use crate::marker::PointeeSized;
1858    use crate::ops::ControlFlow::{self, Break, Continue};
1859
1860    macro_rules! partial_eq_impl {
1861        ($($t:ty)*) => ($(
1862            #[stable(feature = "rust1", since = "1.0.0")]
1863            #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1864            impl const PartialEq for $t {
1865                #[inline]
1866                fn eq(&self, other: &Self) -> bool { *self == *other }
1867                #[inline]
1868                fn ne(&self, other: &Self) -> bool { *self != *other }
1869            }
1870        )*)
1871    }
1872
1873    #[stable(feature = "rust1", since = "1.0.0")]
1874    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1875    impl const PartialEq for () {
1876        #[inline]
1877        fn eq(&self, _other: &()) -> bool {
1878            true
1879        }
1880        #[inline]
1881        fn ne(&self, _other: &()) -> bool {
1882            false
1883        }
1884    }
1885
1886    partial_eq_impl! {
1887        bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128
1888    }
1889
1890    macro_rules! eq_impl {
1891        ($($t:ty)*) => ($(
1892            #[stable(feature = "rust1", since = "1.0.0")]
1893            #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1894            impl const Eq for $t {}
1895        )*)
1896    }
1897
1898    eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1899
1900    #[rustfmt::skip]
1901    macro_rules! partial_ord_methods_primitive_impl {
1902        () => {
1903            #[inline(always)]
1904            fn lt(&self, other: &Self) -> bool { *self <  *other }
1905            #[inline(always)]
1906            fn le(&self, other: &Self) -> bool { *self <= *other }
1907            #[inline(always)]
1908            fn gt(&self, other: &Self) -> bool { *self >  *other }
1909            #[inline(always)]
1910            fn ge(&self, other: &Self) -> bool { *self >= *other }
1911
1912            // These implementations are the same for `Ord` or `PartialOrd` types
1913            // because if either is NAN the `==` test will fail so we end up in
1914            // the `Break` case and the comparison will correctly return `false`.
1915
1916            #[inline]
1917            fn __chaining_lt(&self, other: &Self) -> ControlFlow<bool> {
1918                let (lhs, rhs) = (*self, *other);
1919                if lhs == rhs { Continue(()) } else { Break(lhs < rhs) }
1920            }
1921            #[inline]
1922            fn __chaining_le(&self, other: &Self) -> ControlFlow<bool> {
1923                let (lhs, rhs) = (*self, *other);
1924                if lhs == rhs { Continue(()) } else { Break(lhs <= rhs) }
1925            }
1926            #[inline]
1927            fn __chaining_gt(&self, other: &Self) -> ControlFlow<bool> {
1928                let (lhs, rhs) = (*self, *other);
1929                if lhs == rhs { Continue(()) } else { Break(lhs > rhs) }
1930            }
1931            #[inline]
1932            fn __chaining_ge(&self, other: &Self) -> ControlFlow<bool> {
1933                let (lhs, rhs) = (*self, *other);
1934                if lhs == rhs { Continue(()) } else { Break(lhs >= rhs) }
1935            }
1936        };
1937    }
1938
1939    macro_rules! partial_ord_impl {
1940        ($($t:ty)*) => ($(
1941            #[stable(feature = "rust1", since = "1.0.0")]
1942            #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1943            impl const PartialOrd for $t {
1944                #[inline]
1945                fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1946                    match (*self <= *other, *self >= *other) {
1947                        (false, false) => None,
1948                        (false, true) => Some(Greater),
1949                        (true, false) => Some(Less),
1950                        (true, true) => Some(Equal),
1951                    }
1952                }
1953
1954                partial_ord_methods_primitive_impl!();
1955            }
1956        )*)
1957    }
1958
1959    #[stable(feature = "rust1", since = "1.0.0")]
1960    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1961    impl const PartialOrd for () {
1962        #[inline]
1963        fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1964            Some(Equal)
1965        }
1966    }
1967
1968    #[stable(feature = "rust1", since = "1.0.0")]
1969    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1970    impl const PartialOrd for bool {
1971        #[inline]
1972        fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1973            Some(self.cmp(other))
1974        }
1975
1976        partial_ord_methods_primitive_impl!();
1977    }
1978
1979    partial_ord_impl! { f16 f32 f64 f128 }
1980
1981    macro_rules! ord_impl {
1982        ($($t:ty)*) => ($(
1983            #[stable(feature = "rust1", since = "1.0.0")]
1984            #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1985            impl const PartialOrd for $t {
1986                #[inline]
1987                fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1988                    Some(crate::intrinsics::three_way_compare(*self, *other))
1989                }
1990
1991                partial_ord_methods_primitive_impl!();
1992            }
1993
1994            #[stable(feature = "rust1", since = "1.0.0")]
1995            #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1996            impl const Ord for $t {
1997                #[inline]
1998                fn cmp(&self, other: &Self) -> Ordering {
1999                    crate::intrinsics::three_way_compare(*self, *other)
2000                }
2001            }
2002        )*)
2003    }
2004
2005    #[stable(feature = "rust1", since = "1.0.0")]
2006    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2007    impl const Ord for () {
2008        #[inline]
2009        fn cmp(&self, _other: &()) -> Ordering {
2010            Equal
2011        }
2012    }
2013
2014    #[stable(feature = "rust1", since = "1.0.0")]
2015    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2016    impl const Ord for bool {
2017        #[inline]
2018        fn cmp(&self, other: &bool) -> Ordering {
2019            // Casting to i8's and converting the difference to an Ordering generates
2020            // more optimal assembly.
2021            // See <https://github.com/rust-lang/rust/issues/66780> for more info.
2022            match (*self as i8) - (*other as i8) {
2023                -1 => Less,
2024                0 => Equal,
2025                1 => Greater,
2026                // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
2027                _ => unsafe { unreachable_unchecked() },
2028            }
2029        }
2030
2031        #[inline]
2032        fn min(self, other: bool) -> bool {
2033            self & other
2034        }
2035
2036        #[inline]
2037        fn max(self, other: bool) -> bool {
2038            self | other
2039        }
2040
2041        #[inline]
2042        fn clamp(self, min: bool, max: bool) -> bool {
2043            assert!(min <= max);
2044            self.max(min).min(max)
2045        }
2046    }
2047
2048    ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
2049
2050    #[unstable(feature = "never_type", issue = "35121")]
2051    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2052    impl const PartialEq for ! {
2053        #[inline]
2054        fn eq(&self, _: &!) -> bool {
2055            *self
2056        }
2057    }
2058
2059    #[unstable(feature = "never_type", issue = "35121")]
2060    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2061    impl const Eq for ! {}
2062
2063    #[unstable(feature = "never_type", issue = "35121")]
2064    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2065    impl const PartialOrd for ! {
2066        #[inline]
2067        fn partial_cmp(&self, _: &!) -> Option<Ordering> {
2068            *self
2069        }
2070    }
2071
2072    #[unstable(feature = "never_type", issue = "35121")]
2073    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2074    impl const Ord for ! {
2075        #[inline]
2076        fn cmp(&self, _: &!) -> Ordering {
2077            *self
2078        }
2079    }
2080
2081    // & pointers
2082
2083    #[stable(feature = "rust1", since = "1.0.0")]
2084    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2085    impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &A
2086    where
2087        A: [const] PartialEq<B>,
2088    {
2089        #[inline]
2090        fn eq(&self, other: &&B) -> bool {
2091            PartialEq::eq(*self, *other)
2092        }
2093        #[inline]
2094        fn ne(&self, other: &&B) -> bool {
2095            PartialEq::ne(*self, *other)
2096        }
2097    }
2098    #[stable(feature = "rust1", since = "1.0.0")]
2099    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2100    impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&B> for &A
2101    where
2102        A: [const] PartialOrd<B>,
2103    {
2104        #[inline]
2105        fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
2106            PartialOrd::partial_cmp(*self, *other)
2107        }
2108        #[inline]
2109        fn lt(&self, other: &&B) -> bool {
2110            PartialOrd::lt(*self, *other)
2111        }
2112        #[inline]
2113        fn le(&self, other: &&B) -> bool {
2114            PartialOrd::le(*self, *other)
2115        }
2116        #[inline]
2117        fn gt(&self, other: &&B) -> bool {
2118            PartialOrd::gt(*self, *other)
2119        }
2120        #[inline]
2121        fn ge(&self, other: &&B) -> bool {
2122            PartialOrd::ge(*self, *other)
2123        }
2124        #[inline]
2125        fn __chaining_lt(&self, other: &&B) -> ControlFlow<bool> {
2126            PartialOrd::__chaining_lt(*self, *other)
2127        }
2128        #[inline]
2129        fn __chaining_le(&self, other: &&B) -> ControlFlow<bool> {
2130            PartialOrd::__chaining_le(*self, *other)
2131        }
2132        #[inline]
2133        fn __chaining_gt(&self, other: &&B) -> ControlFlow<bool> {
2134            PartialOrd::__chaining_gt(*self, *other)
2135        }
2136        #[inline]
2137        fn __chaining_ge(&self, other: &&B) -> ControlFlow<bool> {
2138            PartialOrd::__chaining_ge(*self, *other)
2139        }
2140    }
2141    #[stable(feature = "rust1", since = "1.0.0")]
2142    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2143    impl<A: PointeeSized> const Ord for &A
2144    where
2145        A: [const] Ord,
2146    {
2147        #[inline]
2148        fn cmp(&self, other: &Self) -> Ordering {
2149            Ord::cmp(*self, *other)
2150        }
2151    }
2152    #[stable(feature = "rust1", since = "1.0.0")]
2153    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2154    impl<A: PointeeSized> const Eq for &A where A: [const] Eq {}
2155
2156    // &mut pointers
2157
2158    #[stable(feature = "rust1", since = "1.0.0")]
2159    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2160    impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &mut A
2161    where
2162        A: [const] PartialEq<B>,
2163    {
2164        #[inline]
2165        fn eq(&self, other: &&mut B) -> bool {
2166            PartialEq::eq(*self, *other)
2167        }
2168        #[inline]
2169        fn ne(&self, other: &&mut B) -> bool {
2170            PartialEq::ne(*self, *other)
2171        }
2172    }
2173    #[stable(feature = "rust1", since = "1.0.0")]
2174    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2175    impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&mut B> for &mut A
2176    where
2177        A: [const] PartialOrd<B>,
2178    {
2179        #[inline]
2180        fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
2181            PartialOrd::partial_cmp(*self, *other)
2182        }
2183        #[inline]
2184        fn lt(&self, other: &&mut B) -> bool {
2185            PartialOrd::lt(*self, *other)
2186        }
2187        #[inline]
2188        fn le(&self, other: &&mut B) -> bool {
2189            PartialOrd::le(*self, *other)
2190        }
2191        #[inline]
2192        fn gt(&self, other: &&mut B) -> bool {
2193            PartialOrd::gt(*self, *other)
2194        }
2195        #[inline]
2196        fn ge(&self, other: &&mut B) -> bool {
2197            PartialOrd::ge(*self, *other)
2198        }
2199        #[inline]
2200        fn __chaining_lt(&self, other: &&mut B) -> ControlFlow<bool> {
2201            PartialOrd::__chaining_lt(*self, *other)
2202        }
2203        #[inline]
2204        fn __chaining_le(&self, other: &&mut B) -> ControlFlow<bool> {
2205            PartialOrd::__chaining_le(*self, *other)
2206        }
2207        #[inline]
2208        fn __chaining_gt(&self, other: &&mut B) -> ControlFlow<bool> {
2209            PartialOrd::__chaining_gt(*self, *other)
2210        }
2211        #[inline]
2212        fn __chaining_ge(&self, other: &&mut B) -> ControlFlow<bool> {
2213            PartialOrd::__chaining_ge(*self, *other)
2214        }
2215    }
2216    #[stable(feature = "rust1", since = "1.0.0")]
2217    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2218    impl<A: PointeeSized> const Ord for &mut A
2219    where
2220        A: [const] Ord,
2221    {
2222        #[inline]
2223        fn cmp(&self, other: &Self) -> Ordering {
2224            Ord::cmp(*self, *other)
2225        }
2226    }
2227    #[stable(feature = "rust1", since = "1.0.0")]
2228    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2229    impl<A: PointeeSized> const Eq for &mut A where A: [const] Eq {}
2230
2231    #[stable(feature = "rust1", since = "1.0.0")]
2232    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2233    impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &A
2234    where
2235        A: [const] PartialEq<B>,
2236    {
2237        #[inline]
2238        fn eq(&self, other: &&mut B) -> bool {
2239            PartialEq::eq(*self, *other)
2240        }
2241        #[inline]
2242        fn ne(&self, other: &&mut B) -> bool {
2243            PartialEq::ne(*self, *other)
2244        }
2245    }
2246
2247    #[stable(feature = "rust1", since = "1.0.0")]
2248    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2249    impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &mut A
2250    where
2251        A: [const] PartialEq<B>,
2252    {
2253        #[inline]
2254        fn eq(&self, other: &&B) -> bool {
2255            PartialEq::eq(*self, *other)
2256        }
2257        #[inline]
2258        fn ne(&self, other: &&B) -> bool {
2259            PartialEq::ne(*self, *other)
2260        }
2261    }
2262}