Skip to main content

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