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