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