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