Skip to main content

core/
cmp.rs

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