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#[rustc_on_unimplemented(
245    message = "can't compare `{Self}` with `{Rhs}`",
246    label = "no implementation for `{Self} == {Rhs}`",
247    append_const_msg
248)]
249#[rustc_diagnostic_item = "PartialEq"]
250#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
251pub const trait PartialEq<Rhs: PointeeSized = Self>: PointeeSized {
252    /// Tests for `self` and `other` values to be equal, and is used by `==`.
253    #[must_use]
254    #[stable(feature = "rust1", since = "1.0.0")]
255    #[rustc_diagnostic_item = "cmp_partialeq_eq"]
256    fn eq(&self, other: &Rhs) -> bool;
257
258    /// Tests for `!=`. The default implementation is almost always sufficient,
259    /// and should not be overridden without very good reason.
260    #[inline]
261    #[must_use]
262    #[stable(feature = "rust1", since = "1.0.0")]
263    #[rustc_diagnostic_item = "cmp_partialeq_ne"]
264    #[ferrocene::prevalidated]
265    fn ne(&self, other: &Rhs) -> bool {
266        !self.eq(other)
267    }
268}
269
270/// Derive macro generating an impl of the trait [`PartialEq`].
271/// The behavior of this macro is described in detail [here](PartialEq#derivable).
272#[rustc_builtin_macro]
273#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
274#[allow_internal_unstable(core_intrinsics, structural_match)]
275pub macro PartialEq($item:item) {
276    /* compiler built-in */
277}
278
279/// Trait for comparisons corresponding to [equivalence relations](
280/// https://en.wikipedia.org/wiki/Equivalence_relation).
281///
282/// The primary difference to [`PartialEq`] is the additional requirement for reflexivity. A type
283/// that implements [`PartialEq`] guarantees that for all `a`, `b` and `c`:
284///
285/// - symmetric: `a == b` implies `b == a` and `a != b` implies `!(a == b)`
286/// - transitive: `a == b` and `b == c` implies `a == c`
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#[rustc_builtin_macro]
364#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
365#[allow_internal_unstable(core_intrinsics, derive_eq_internals, structural_match)]
366#[allow_internal_unstable(coverage_attribute)]
367pub macro Eq($item:item) {
368    /* compiler built-in */
369}
370
371// FIXME: this struct is used solely by #[derive] to
372// assert that every component of a type implements Eq.
373//
374// This struct should never appear in user code.
375#[doc(hidden)]
376#[allow(missing_debug_implementations)]
377#[unstable(
378    feature = "derive_eq_internals",
379    reason = "deriving hack, should not be public",
380    issue = "none"
381)]
382#[ferrocene::prevalidated]
383pub struct AssertParamIsEq<T: Eq + PointeeSized> {
384    _field: crate::marker::PhantomData<T>,
385}
386
387/// An `Ordering` is the result of a comparison between two values.
388///
389/// # Examples
390///
391/// ```
392/// use std::cmp::Ordering;
393///
394/// assert_eq!(1.cmp(&2), Ordering::Less);
395///
396/// assert_eq!(1.cmp(&1), Ordering::Equal);
397///
398/// assert_eq!(2.cmp(&1), Ordering::Greater);
399/// ```
400#[derive(Copy, Debug, Hash)]
401#[derive_const(Clone, Eq, PartialOrd, Ord, PartialEq)]
402#[stable(feature = "rust1", since = "1.0.0")]
403// This is a lang item only so that `BinOp::Cmp` in MIR can return it.
404// It has no special behavior, but does require that the three variants
405// `Less`/`Equal`/`Greater` remain `-1_i8`/`0_i8`/`+1_i8` respectively.
406#[lang = "Ordering"]
407#[repr(i8)]
408#[ferrocene::prevalidated]
409pub enum Ordering {
410    /// An ordering where a compared value is less than another.
411    #[stable(feature = "rust1", since = "1.0.0")]
412    Less = -1,
413    /// An ordering where a compared value is equal to another.
414    #[stable(feature = "rust1", since = "1.0.0")]
415    Equal = 0,
416    /// An ordering where a compared value is greater than another.
417    #[stable(feature = "rust1", since = "1.0.0")]
418    Greater = 1,
419}
420
421impl Ordering {
422    #[inline]
423    #[ferrocene::prevalidated]
424    const fn as_raw(self) -> i8 {
425        // FIXME(const-hack): just use `PartialOrd` against `Equal` once that's const
426        crate::intrinsics::discriminant_value(&self)
427    }
428
429    /// Returns `true` if the ordering is the `Equal` variant.
430    ///
431    /// # Examples
432    ///
433    /// ```
434    /// use std::cmp::Ordering;
435    ///
436    /// assert_eq!(Ordering::Less.is_eq(), false);
437    /// assert_eq!(Ordering::Equal.is_eq(), true);
438    /// assert_eq!(Ordering::Greater.is_eq(), false);
439    /// ```
440    #[inline]
441    #[must_use]
442    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
443    #[stable(feature = "ordering_helpers", since = "1.53.0")]
444    #[ferrocene::prevalidated]
445    pub const fn is_eq(self) -> bool {
446        // All the `is_*` methods are implemented as comparisons against zero
447        // to follow how clang's libcxx implements their equivalents in
448        // <https://github.com/llvm/llvm-project/blob/60486292b79885b7800b082754153202bef5b1f0/libcxx/include/__compare/is_eq.h#L23-L28>
449
450        self.as_raw() == 0
451    }
452
453    /// Returns `true` if the ordering is not the `Equal` variant.
454    ///
455    /// # Examples
456    ///
457    /// ```
458    /// use std::cmp::Ordering;
459    ///
460    /// assert_eq!(Ordering::Less.is_ne(), true);
461    /// assert_eq!(Ordering::Equal.is_ne(), false);
462    /// assert_eq!(Ordering::Greater.is_ne(), true);
463    /// ```
464    #[inline]
465    #[must_use]
466    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
467    #[stable(feature = "ordering_helpers", since = "1.53.0")]
468    #[ferrocene::prevalidated]
469    pub const fn is_ne(self) -> bool {
470        self.as_raw() != 0
471    }
472
473    /// Returns `true` if the ordering is the `Less` variant.
474    ///
475    /// # Examples
476    ///
477    /// ```
478    /// use std::cmp::Ordering;
479    ///
480    /// assert_eq!(Ordering::Less.is_lt(), true);
481    /// assert_eq!(Ordering::Equal.is_lt(), false);
482    /// assert_eq!(Ordering::Greater.is_lt(), false);
483    /// ```
484    #[inline]
485    #[must_use]
486    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
487    #[stable(feature = "ordering_helpers", since = "1.53.0")]
488    #[ferrocene::prevalidated]
489    pub const fn is_lt(self) -> bool {
490        self.as_raw() < 0
491    }
492
493    /// Returns `true` if the ordering is the `Greater` variant.
494    ///
495    /// # Examples
496    ///
497    /// ```
498    /// use std::cmp::Ordering;
499    ///
500    /// assert_eq!(Ordering::Less.is_gt(), false);
501    /// assert_eq!(Ordering::Equal.is_gt(), false);
502    /// assert_eq!(Ordering::Greater.is_gt(), true);
503    /// ```
504    #[inline]
505    #[must_use]
506    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
507    #[stable(feature = "ordering_helpers", since = "1.53.0")]
508    #[ferrocene::prevalidated]
509    pub const fn is_gt(self) -> bool {
510        self.as_raw() > 0
511    }
512
513    /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
514    ///
515    /// # Examples
516    ///
517    /// ```
518    /// use std::cmp::Ordering;
519    ///
520    /// assert_eq!(Ordering::Less.is_le(), true);
521    /// assert_eq!(Ordering::Equal.is_le(), true);
522    /// assert_eq!(Ordering::Greater.is_le(), false);
523    /// ```
524    #[inline]
525    #[must_use]
526    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
527    #[stable(feature = "ordering_helpers", since = "1.53.0")]
528    #[ferrocene::prevalidated]
529    pub const fn is_le(self) -> bool {
530        self.as_raw() <= 0
531    }
532
533    /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
534    ///
535    /// # Examples
536    ///
537    /// ```
538    /// use std::cmp::Ordering;
539    ///
540    /// assert_eq!(Ordering::Less.is_ge(), false);
541    /// assert_eq!(Ordering::Equal.is_ge(), true);
542    /// assert_eq!(Ordering::Greater.is_ge(), true);
543    /// ```
544    #[inline]
545    #[must_use]
546    #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
547    #[stable(feature = "ordering_helpers", since = "1.53.0")]
548    #[ferrocene::prevalidated]
549    pub const fn is_ge(self) -> bool {
550        self.as_raw() >= 0
551    }
552
553    /// Reverses the `Ordering`.
554    ///
555    /// * `Less` becomes `Greater`.
556    /// * `Greater` becomes `Less`.
557    /// * `Equal` becomes `Equal`.
558    ///
559    /// # Examples
560    ///
561    /// Basic behavior:
562    ///
563    /// ```
564    /// use std::cmp::Ordering;
565    ///
566    /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
567    /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
568    /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
569    /// ```
570    ///
571    /// This method can be used to reverse a comparison:
572    ///
573    /// ```
574    /// let data: &mut [_] = &mut [2, 10, 5, 8];
575    ///
576    /// // sort the array from largest to smallest.
577    /// data.sort_by(|a, b| a.cmp(b).reverse());
578    ///
579    /// let b: &mut [_] = &mut [10, 8, 5, 2];
580    /// assert!(data == b);
581    /// ```
582    #[inline]
583    #[must_use]
584    #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
585    #[stable(feature = "rust1", since = "1.0.0")]
586    #[ferrocene::prevalidated]
587    pub const fn reverse(self) -> Ordering {
588        match self {
589            Less => Greater,
590            Equal => Equal,
591            Greater => Less,
592        }
593    }
594
595    /// Chains two orderings.
596    ///
597    /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
598    ///
599    /// # Examples
600    ///
601    /// ```
602    /// use std::cmp::Ordering;
603    ///
604    /// let result = Ordering::Equal.then(Ordering::Less);
605    /// assert_eq!(result, Ordering::Less);
606    ///
607    /// let result = Ordering::Less.then(Ordering::Equal);
608    /// assert_eq!(result, Ordering::Less);
609    ///
610    /// let result = Ordering::Less.then(Ordering::Greater);
611    /// assert_eq!(result, Ordering::Less);
612    ///
613    /// let result = Ordering::Equal.then(Ordering::Equal);
614    /// assert_eq!(result, Ordering::Equal);
615    ///
616    /// let x: (i64, i64, i64) = (1, 2, 7);
617    /// let y: (i64, i64, i64) = (1, 5, 3);
618    /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
619    ///
620    /// assert_eq!(result, Ordering::Less);
621    /// ```
622    #[inline]
623    #[must_use]
624    #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
625    #[stable(feature = "ordering_chaining", since = "1.17.0")]
626    #[ferrocene::prevalidated]
627    pub const fn then(self, other: Ordering) -> Ordering {
628        match self {
629            Equal => other,
630            _ => self,
631        }
632    }
633
634    /// Chains the ordering with the given function.
635    ///
636    /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
637    /// the result.
638    ///
639    /// # Examples
640    ///
641    /// ```
642    /// use std::cmp::Ordering;
643    ///
644    /// let result = Ordering::Equal.then_with(|| Ordering::Less);
645    /// assert_eq!(result, Ordering::Less);
646    ///
647    /// let result = Ordering::Less.then_with(|| Ordering::Equal);
648    /// assert_eq!(result, Ordering::Less);
649    ///
650    /// let result = Ordering::Less.then_with(|| Ordering::Greater);
651    /// assert_eq!(result, Ordering::Less);
652    ///
653    /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
654    /// assert_eq!(result, Ordering::Equal);
655    ///
656    /// let x: (i64, i64, i64) = (1, 2, 7);
657    /// let y: (i64, i64, i64) = (1, 5, 3);
658    /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
659    ///
660    /// assert_eq!(result, Ordering::Less);
661    /// ```
662    #[inline]
663    #[must_use]
664    #[stable(feature = "ordering_chaining", since = "1.17.0")]
665    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
666    pub const fn then_with<F>(self, f: F) -> Ordering
667    where
668        F: [const] FnOnce() -> Ordering + [const] Destruct,
669    {
670        match self {
671            Equal => f(),
672            _ => self,
673        }
674    }
675}
676
677/// A helper struct for reverse ordering.
678///
679/// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
680/// can be used to reverse order a part of a key.
681///
682/// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
683///
684/// # Examples
685///
686/// ```
687/// use std::cmp::Reverse;
688///
689/// let mut v = vec![1, 2, 3, 4, 5, 6];
690/// v.sort_by_key(|&num| (num > 3, Reverse(num)));
691/// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
692/// ```
693#[derive(Copy, Debug, Hash)]
694#[derive_const(PartialEq, Eq, Default)]
695#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
696#[repr(transparent)]
697pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
698
699#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
700#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
701impl<T: [const] PartialOrd> const PartialOrd for Reverse<T> {
702    #[inline]
703    fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
704        other.0.partial_cmp(&self.0)
705    }
706
707    #[inline]
708    fn lt(&self, other: &Self) -> bool {
709        other.0 < self.0
710    }
711    #[inline]
712    fn le(&self, other: &Self) -> bool {
713        other.0 <= self.0
714    }
715    #[inline]
716    fn gt(&self, other: &Self) -> bool {
717        other.0 > self.0
718    }
719    #[inline]
720    fn ge(&self, other: &Self) -> bool {
721        other.0 >= self.0
722    }
723}
724
725#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
726#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
727impl<T: [const] Ord> const Ord for Reverse<T> {
728    #[inline]
729    fn cmp(&self, other: &Reverse<T>) -> Ordering {
730        other.0.cmp(&self.0)
731    }
732}
733
734#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
735impl<T: Clone> Clone for Reverse<T> {
736    #[inline]
737    fn clone(&self) -> Reverse<T> {
738        Reverse(self.0.clone())
739    }
740
741    #[inline]
742    fn clone_from(&mut self, source: &Self) {
743        self.0.clone_from(&source.0)
744    }
745}
746
747/// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
748///
749/// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure `max`,
750/// `min`, and `clamp` are consistent with `cmp`:
751///
752/// - `partial_cmp(a, b) == Some(cmp(a, b))`.
753/// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
754/// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
755/// - For `a.clamp(min, max)`, see the [method docs](#method.clamp) (ensured by the default
756///   implementation).
757///
758/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
759/// specified, but users of the trait must ensure that such logic errors do *not* result in
760/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
761/// methods.
762///
763/// ## Corollaries
764///
765/// From the above and the requirements of `PartialOrd`, it follows that for all `a`, `b` and `c`:
766///
767/// - exactly one of `a < b`, `a == b` or `a > b` is true; and
768/// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and
769///   `>`.
770///
771/// Mathematically speaking, the `<` operator defines a strict [weak order]. In cases where `==`
772/// conforms to mathematical equality, it also defines a strict [total order].
773///
774/// [weak order]: https://en.wikipedia.org/wiki/Weak_ordering
775/// [total order]: https://en.wikipedia.org/wiki/Total_order
776///
777/// ## Derivable
778///
779/// This trait can be used with `#[derive]`.
780///
781/// When `derive`d on structs, it will produce a
782/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the
783/// top-to-bottom declaration order of the struct's members.
784///
785/// When `derive`d on enums, variants are ordered primarily by their discriminants. Secondarily,
786/// they are ordered by their fields. By default, the discriminant is smallest for variants at the
787/// top, and largest for variants at the bottom. Here's an example:
788///
789/// ```
790/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
791/// enum E {
792///     Top,
793///     Bottom,
794/// }
795///
796/// assert!(E::Top < E::Bottom);
797/// ```
798///
799/// However, manually setting the discriminants can override this default behavior:
800///
801/// ```
802/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
803/// enum E {
804///     Top = 2,
805///     Bottom = 1,
806/// }
807///
808/// assert!(E::Bottom < E::Top);
809/// ```
810///
811/// ## Lexicographical comparison
812///
813/// Lexicographical comparison is an operation with the following properties:
814///  - Two sequences are compared element by element.
815///  - The first mismatching element defines which sequence is lexicographically less or greater
816///    than the other.
817///  - If one sequence is a prefix of another, the shorter sequence is lexicographically less than
818///    the other.
819///  - If two sequences have equivalent elements and are of the same length, then the sequences are
820///    lexicographically equal.
821///  - An empty sequence is lexicographically less than any non-empty sequence.
822///  - Two empty sequences are lexicographically equal.
823///
824/// ## How can I implement `Ord`?
825///
826/// `Ord` requires that the type also be [`PartialOrd`], [`PartialEq`], and [`Eq`].
827///
828/// Because `Ord` implies a stronger ordering relationship than [`PartialOrd`], and both `Ord` and
829/// [`PartialOrd`] must agree, you must choose how to implement `Ord` **first**. You can choose to
830/// derive it, or implement it manually. If you derive it, you should derive all four traits. If you
831/// implement it manually, you should manually implement all four traits, based on the
832/// implementation of `Ord`.
833///
834/// Here's an example where you want to define the `Character` comparison by `health` and
835/// `experience` only, disregarding the field `mana`:
836///
837/// ```
838/// use std::cmp::Ordering;
839///
840/// struct Character {
841///     health: u32,
842///     experience: u32,
843///     mana: f32,
844/// }
845///
846/// impl Ord for Character {
847///     fn cmp(&self, other: &Self) -> Ordering {
848///         self.experience
849///             .cmp(&other.experience)
850///             .then(self.health.cmp(&other.health))
851///     }
852/// }
853///
854/// impl PartialOrd for Character {
855///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
856///         Some(self.cmp(other))
857///     }
858/// }
859///
860/// impl PartialEq for Character {
861///     fn eq(&self, other: &Self) -> bool {
862///         self.health == other.health && self.experience == other.experience
863///     }
864/// }
865///
866/// impl Eq for Character {}
867/// ```
868///
869/// If all you need is to `slice::sort` a type by a field value, it can be simpler to use
870/// `slice::sort_by_key`.
871///
872/// ## Examples of incorrect `Ord` implementations
873///
874/// ```
875/// use std::cmp::Ordering;
876///
877/// #[derive(Debug)]
878/// struct Character {
879///     health: f32,
880/// }
881///
882/// impl Ord for Character {
883///     fn cmp(&self, other: &Self) -> std::cmp::Ordering {
884///         if self.health < other.health {
885///             Ordering::Less
886///         } else if self.health > other.health {
887///             Ordering::Greater
888///         } else {
889///             Ordering::Equal
890///         }
891///     }
892/// }
893///
894/// impl PartialOrd for Character {
895///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
896///         Some(self.cmp(other))
897///     }
898/// }
899///
900/// impl PartialEq for Character {
901///     fn eq(&self, other: &Self) -> bool {
902///         self.health == other.health
903///     }
904/// }
905///
906/// impl Eq for Character {}
907///
908/// let a = Character { health: 4.5 };
909/// let b = Character { health: f32::NAN };
910///
911/// // Mistake: floating-point values do not form a total order and using the built-in comparison
912/// // operands to implement `Ord` irregardless of that reality does not change it. Use
913/// // `f32::total_cmp` if you need a total order for floating-point values.
914///
915/// // Reflexivity requirement of `Ord` is not given.
916/// assert!(a == a);
917/// assert!(b != b);
918///
919/// // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be
920/// // true, not both or neither.
921/// assert_eq!((a < b) as u8 + (b < a) as u8, 0);
922/// ```
923///
924/// ```
925/// use std::cmp::Ordering;
926///
927/// #[derive(Debug)]
928/// struct Character {
929///     health: u32,
930///     experience: u32,
931/// }
932///
933/// impl PartialOrd for Character {
934///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
935///         Some(self.cmp(other))
936///     }
937/// }
938///
939/// impl Ord for Character {
940///     fn cmp(&self, other: &Self) -> std::cmp::Ordering {
941///         if self.health < 50 {
942///             self.health.cmp(&other.health)
943///         } else {
944///             self.experience.cmp(&other.experience)
945///         }
946///     }
947/// }
948///
949/// // For performance reasons implementing `PartialEq` this way is not the idiomatic way, but it
950/// // ensures consistent behavior between `PartialEq`, `PartialOrd` and `Ord` in this example.
951/// impl PartialEq for Character {
952///     fn eq(&self, other: &Self) -> bool {
953///         self.cmp(other) == Ordering::Equal
954///     }
955/// }
956///
957/// impl Eq for Character {}
958///
959/// let a = Character {
960///     health: 3,
961///     experience: 5,
962/// };
963/// let b = Character {
964///     health: 10,
965///     experience: 77,
966/// };
967/// let c = Character {
968///     health: 143,
969///     experience: 2,
970/// };
971///
972/// // Mistake: The implementation of `Ord` compares different fields depending on the value of
973/// // `self.health`, the resulting order is not total.
974///
975/// // Transitivity requirement of `Ord` is not given. If a is smaller than b and b is smaller than
976/// // c, by transitive property a must also be smaller than c.
977/// assert!(a < b && b < c && c < a);
978///
979/// // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be
980/// // true, not both or neither.
981/// assert_eq!((a < c) as u8 + (c < a) as u8, 2);
982/// ```
983///
984/// The documentation of [`PartialOrd`] contains further examples, for example it's wrong for
985/// [`PartialOrd`] and [`PartialEq`] to disagree.
986///
987/// [`cmp`]: Ord::cmp
988#[doc(alias = "<")]
989#[doc(alias = ">")]
990#[doc(alias = "<=")]
991#[doc(alias = ">=")]
992#[stable(feature = "rust1", since = "1.0.0")]
993#[rustc_diagnostic_item = "Ord"]
994#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
995pub const trait Ord: [const] Eq + [const] PartialOrd<Self> + PointeeSized {
996    /// This method returns an [`Ordering`] between `self` and `other`.
997    ///
998    /// By convention, `self.cmp(&other)` returns the ordering matching the expression
999    /// `self <operator> other` if true.
1000    ///
1001    /// # Examples
1002    ///
1003    /// ```
1004    /// use std::cmp::Ordering;
1005    ///
1006    /// assert_eq!(5.cmp(&10), Ordering::Less);
1007    /// assert_eq!(10.cmp(&5), Ordering::Greater);
1008    /// assert_eq!(5.cmp(&5), Ordering::Equal);
1009    /// ```
1010    #[must_use]
1011    #[stable(feature = "rust1", since = "1.0.0")]
1012    #[rustc_diagnostic_item = "ord_cmp_method"]
1013    fn cmp(&self, other: &Self) -> Ordering;
1014
1015    /// Compares and returns the maximum of two values.
1016    ///
1017    /// Returns the second argument if the comparison determines them to be equal.
1018    ///
1019    /// # Examples
1020    ///
1021    /// ```
1022    /// assert_eq!(1.max(2), 2);
1023    /// assert_eq!(2.max(2), 2);
1024    /// ```
1025    /// ```
1026    /// use std::cmp::Ordering;
1027    ///
1028    /// #[derive(Eq)]
1029    /// struct Equal(&'static str);
1030    ///
1031    /// impl PartialEq for Equal {
1032    ///     fn eq(&self, other: &Self) -> bool { true }
1033    /// }
1034    /// impl PartialOrd for Equal {
1035    ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1036    /// }
1037    /// impl Ord for Equal {
1038    ///     fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1039    /// }
1040    ///
1041    /// assert_eq!(Equal("self").max(Equal("other")).0, "other");
1042    /// ```
1043    #[stable(feature = "ord_max_min", since = "1.21.0")]
1044    #[inline]
1045    #[must_use]
1046    #[rustc_diagnostic_item = "cmp_ord_max"]
1047    #[ferrocene::prevalidated]
1048    fn max(self, other: Self) -> Self
1049    where
1050        Self: Sized + [const] Destruct,
1051    {
1052        if other < self { self } else { other }
1053    }
1054
1055    /// Compares and returns the minimum of two values.
1056    ///
1057    /// Returns the first argument if the comparison determines them to be equal.
1058    ///
1059    /// # Examples
1060    ///
1061    /// ```
1062    /// assert_eq!(1.min(2), 1);
1063    /// assert_eq!(2.min(2), 2);
1064    /// ```
1065    /// ```
1066    /// use std::cmp::Ordering;
1067    ///
1068    /// #[derive(Eq)]
1069    /// struct Equal(&'static str);
1070    ///
1071    /// impl PartialEq for Equal {
1072    ///     fn eq(&self, other: &Self) -> bool { true }
1073    /// }
1074    /// impl PartialOrd for Equal {
1075    ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1076    /// }
1077    /// impl Ord for Equal {
1078    ///     fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1079    /// }
1080    ///
1081    /// assert_eq!(Equal("self").min(Equal("other")).0, "self");
1082    /// ```
1083    #[stable(feature = "ord_max_min", since = "1.21.0")]
1084    #[inline]
1085    #[must_use]
1086    #[rustc_diagnostic_item = "cmp_ord_min"]
1087    #[ferrocene::prevalidated]
1088    fn min(self, other: Self) -> Self
1089    where
1090        Self: Sized + [const] Destruct,
1091    {
1092        if other < self { other } else { self }
1093    }
1094
1095    /// Restrict a value to a certain interval.
1096    ///
1097    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1098    /// less than `min`. Otherwise this returns `self`.
1099    ///
1100    /// # Panics
1101    ///
1102    /// Panics if `min > max`.
1103    ///
1104    /// # Examples
1105    ///
1106    /// ```
1107    /// assert_eq!((-3).clamp(-2, 1), -2);
1108    /// assert_eq!(0.clamp(-2, 1), 0);
1109    /// assert_eq!(2.clamp(-2, 1), 1);
1110    /// ```
1111    #[must_use]
1112    #[inline]
1113    #[stable(feature = "clamp", since = "1.50.0")]
1114    #[ferrocene::prevalidated]
1115    fn clamp(self, min: Self, max: Self) -> Self
1116    where
1117        Self: Sized + [const] Destruct,
1118    {
1119        assert!(min <= max);
1120        if self < min {
1121            min
1122        } else if self > max {
1123            max
1124        } else {
1125            self
1126        }
1127    }
1128}
1129
1130/// Derive macro generating an impl of the trait [`Ord`].
1131/// The behavior of this macro is described in detail [here](Ord#derivable).
1132#[rustc_builtin_macro]
1133#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1134#[allow_internal_unstable(core_intrinsics)]
1135pub macro Ord($item:item) {
1136    /* compiler built-in */
1137}
1138
1139/// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
1140///
1141/// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using the `<`, `<=`, `>`, and
1142/// `>=` operators, respectively.
1143///
1144/// This trait should **only** contain the comparison logic for a type **if one plans on only
1145/// implementing `PartialOrd` but not [`Ord`]**. Otherwise the comparison logic should be in [`Ord`]
1146/// and this trait implemented with `Some(self.cmp(other))`.
1147///
1148/// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
1149/// The following conditions must hold:
1150///
1151/// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
1152/// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
1153/// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
1154/// 4. `a <= b` if and only if `a < b || a == b`
1155/// 5. `a >= b` if and only if `a > b || a == b`
1156/// 6. `a != b` if and only if `!(a == b)`.
1157///
1158/// Conditions 2–5 above are ensured by the default implementation. Condition 6 is already ensured
1159/// by [`PartialEq`].
1160///
1161/// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
1162/// `partial_cmp` (see the documentation of that trait for the exact requirements). It's easy to
1163/// accidentally make them disagree by deriving some of the traits and manually implementing others.
1164///
1165/// The comparison relations must satisfy the following conditions (for all `a`, `b`, `c` of type
1166/// `A`, `B`, `C`):
1167///
1168/// - **Transitivity**: if `A: PartialOrd<B>` and `B: PartialOrd<C>` and `A: PartialOrd<C>`, then `a
1169///   < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. This must also
1170///   work for longer chains, such as when `A: PartialOrd<B>`, `B: PartialOrd<C>`, `C:
1171///   PartialOrd<D>`, and `A: PartialOrd<D>` all exist.
1172/// - **Duality**: if `A: PartialOrd<B>` and `B: PartialOrd<A>`, then `a < b` if and only if `b >
1173///   a`.
1174///
1175/// Note that the `B: PartialOrd<A>` (dual) and `A: PartialOrd<C>` (transitive) impls are not forced
1176/// to exist, but these requirements apply whenever they do exist.
1177///
1178/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
1179/// specified, but users of the trait must ensure that such logic errors do *not* result in
1180/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
1181/// methods.
1182///
1183/// ## Cross-crate considerations
1184///
1185/// Upholding the requirements stated above can become tricky when one crate implements `PartialOrd`
1186/// for a type of another crate (i.e., to allow comparing one of its own types with a type from the
1187/// standard library). The recommendation is to never implement this trait for a foreign type. In
1188/// other words, such a crate should do `impl PartialOrd<ForeignType> for LocalType`, but it should
1189/// *not* do `impl PartialOrd<LocalType> for ForeignType`.
1190///
1191/// This avoids the problem of transitive chains that criss-cross crate boundaries: for all local
1192/// types `T`, you may assume that no other crate will add `impl`s that allow comparing `T < U`. In
1193/// other words, if other crates add `impl`s that allow building longer transitive chains `U1 < ...
1194/// < T < V1 < ...`, then all the types that appear to the right of `T` must be types that the crate
1195/// defining `T` already knows about. This rules out transitive chains where downstream crates can
1196/// add new `impl`s that "stitch together" comparisons of foreign types in ways that violate
1197/// transitivity.
1198///
1199/// Not having such foreign `impl`s also avoids forward compatibility issues where one crate adding
1200/// more `PartialOrd` implementations can cause build failures in downstream crates.
1201///
1202/// ## Corollaries
1203///
1204/// The following corollaries follow from the above requirements:
1205///
1206/// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
1207/// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
1208/// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
1209///
1210/// ## Strict and non-strict partial orders
1211///
1212/// The `<` and `>` operators behave according to a *strict* partial order. However, `<=` and `>=`
1213/// do **not** behave according to a *non-strict* partial order. That is because mathematically, a
1214/// non-strict partial order would require reflexivity, i.e. `a <= a` would need to be true for
1215/// every `a`. This isn't always the case for types that implement `PartialOrd`, for example:
1216///
1217/// ```
1218/// let a = f64::NAN;
1219/// assert_eq!(a <= a, false);
1220/// ```
1221///
1222/// ## Derivable
1223///
1224/// This trait can be used with `#[derive]`.
1225///
1226/// When `derive`d on structs, it will produce a
1227/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the
1228/// top-to-bottom declaration order of the struct's members.
1229///
1230/// When `derive`d on enums, variants are primarily ordered by their discriminants. Secondarily,
1231/// they are ordered by their fields. By default, the discriminant is smallest for variants at the
1232/// top, and largest for variants at the bottom. Here's an example:
1233///
1234/// ```
1235/// #[derive(PartialEq, PartialOrd)]
1236/// enum E {
1237///     Top,
1238///     Bottom,
1239/// }
1240///
1241/// assert!(E::Top < E::Bottom);
1242/// ```
1243///
1244/// However, manually setting the discriminants can override this default behavior:
1245///
1246/// ```
1247/// #[derive(PartialEq, PartialOrd)]
1248/// enum E {
1249///     Top = 2,
1250///     Bottom = 1,
1251/// }
1252///
1253/// assert!(E::Bottom < E::Top);
1254/// ```
1255///
1256/// ## How can I implement `PartialOrd`?
1257///
1258/// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
1259/// generated from default implementations.
1260///
1261/// However it remains possible to implement the others separately for types which do not have a
1262/// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 == false`
1263/// (cf. IEEE 754-2008 section 5.11).
1264///
1265/// `PartialOrd` requires your type to be [`PartialEq`].
1266///
1267/// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
1268///
1269/// ```
1270/// use std::cmp::Ordering;
1271///
1272/// struct Person {
1273///     id: u32,
1274///     name: String,
1275///     height: u32,
1276/// }
1277///
1278/// impl PartialOrd for Person {
1279///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1280///         Some(self.cmp(other))
1281///     }
1282/// }
1283///
1284/// impl Ord for Person {
1285///     fn cmp(&self, other: &Self) -> Ordering {
1286///         self.height.cmp(&other.height)
1287///     }
1288/// }
1289///
1290/// impl PartialEq for Person {
1291///     fn eq(&self, other: &Self) -> bool {
1292///         self.height == other.height
1293///     }
1294/// }
1295///
1296/// impl Eq for Person {}
1297/// ```
1298///
1299/// You may also find it useful to use [`partial_cmp`] on your type's fields. Here is an example of
1300/// `Person` types who have a floating-point `height` field that is the only field to be used for
1301/// sorting:
1302///
1303/// ```
1304/// use std::cmp::Ordering;
1305///
1306/// struct Person {
1307///     id: u32,
1308///     name: String,
1309///     height: f64,
1310/// }
1311///
1312/// impl PartialOrd for Person {
1313///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1314///         self.height.partial_cmp(&other.height)
1315///     }
1316/// }
1317///
1318/// impl PartialEq for Person {
1319///     fn eq(&self, other: &Self) -> bool {
1320///         self.height == other.height
1321///     }
1322/// }
1323/// ```
1324///
1325/// ## Examples of incorrect `PartialOrd` implementations
1326///
1327/// ```
1328/// use std::cmp::Ordering;
1329///
1330/// #[derive(PartialEq, Debug)]
1331/// struct Character {
1332///     health: u32,
1333///     experience: u32,
1334/// }
1335///
1336/// impl PartialOrd for Character {
1337///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1338///         Some(self.health.cmp(&other.health))
1339///     }
1340/// }
1341///
1342/// let a = Character {
1343///     health: 10,
1344///     experience: 5,
1345/// };
1346/// let b = Character {
1347///     health: 10,
1348///     experience: 77,
1349/// };
1350///
1351/// // Mistake: `PartialEq` and `PartialOrd` disagree with each other.
1352///
1353/// assert_eq!(a.partial_cmp(&b).unwrap(), Ordering::Equal); // a == b according to `PartialOrd`.
1354/// assert_ne!(a, b); // a != b according to `PartialEq`.
1355/// ```
1356///
1357/// # Examples
1358///
1359/// ```
1360/// let x: u32 = 0;
1361/// let y: u32 = 1;
1362///
1363/// assert_eq!(x < y, true);
1364/// assert_eq!(x.lt(&y), true);
1365/// ```
1366///
1367/// [`partial_cmp`]: PartialOrd::partial_cmp
1368/// [`cmp`]: Ord::cmp
1369#[lang = "partial_ord"]
1370#[stable(feature = "rust1", since = "1.0.0")]
1371#[doc(alias = ">")]
1372#[doc(alias = "<")]
1373#[doc(alias = "<=")]
1374#[doc(alias = ">=")]
1375#[rustc_on_unimplemented(
1376    message = "can't compare `{Self}` with `{Rhs}`",
1377    label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1378    append_const_msg
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        fn cmp(&self, other: &Self) -> Ordering {
2249            Ord::cmp(*self, *other)
2250        }
2251    }
2252    #[stable(feature = "rust1", since = "1.0.0")]
2253    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2254    impl<A: PointeeSized> const Eq for &A where A: [const] Eq {}
2255
2256    // &mut pointers
2257
2258    #[stable(feature = "rust1", since = "1.0.0")]
2259    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2260    impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &mut A
2261    where
2262        A: [const] PartialEq<B>,
2263    {
2264        #[inline]
2265        #[ferrocene::prevalidated]
2266        fn eq(&self, other: &&mut B) -> bool {
2267            PartialEq::eq(*self, *other)
2268        }
2269        #[inline]
2270        #[ferrocene::prevalidated]
2271        fn ne(&self, other: &&mut B) -> bool {
2272            PartialEq::ne(*self, *other)
2273        }
2274    }
2275    #[stable(feature = "rust1", since = "1.0.0")]
2276    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2277    impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&mut B> for &mut A
2278    where
2279        A: [const] PartialOrd<B>,
2280    {
2281        #[inline]
2282        fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
2283            PartialOrd::partial_cmp(*self, *other)
2284        }
2285        #[inline]
2286        fn lt(&self, other: &&mut B) -> bool {
2287            PartialOrd::lt(*self, *other)
2288        }
2289        #[inline]
2290        fn le(&self, other: &&mut B) -> bool {
2291            PartialOrd::le(*self, *other)
2292        }
2293        #[inline]
2294        fn gt(&self, other: &&mut B) -> bool {
2295            PartialOrd::gt(*self, *other)
2296        }
2297        #[inline]
2298        fn ge(&self, other: &&mut B) -> bool {
2299            PartialOrd::ge(*self, *other)
2300        }
2301        #[inline]
2302        fn __chaining_lt(&self, other: &&mut B) -> ControlFlow<bool> {
2303            PartialOrd::__chaining_lt(*self, *other)
2304        }
2305        #[inline]
2306        fn __chaining_le(&self, other: &&mut B) -> ControlFlow<bool> {
2307            PartialOrd::__chaining_le(*self, *other)
2308        }
2309        #[inline]
2310        fn __chaining_gt(&self, other: &&mut B) -> ControlFlow<bool> {
2311            PartialOrd::__chaining_gt(*self, *other)
2312        }
2313        #[inline]
2314        fn __chaining_ge(&self, other: &&mut B) -> ControlFlow<bool> {
2315            PartialOrd::__chaining_ge(*self, *other)
2316        }
2317    }
2318    #[stable(feature = "rust1", since = "1.0.0")]
2319    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2320    impl<A: PointeeSized> const Ord for &mut A
2321    where
2322        A: [const] Ord,
2323    {
2324        #[inline]
2325        fn cmp(&self, other: &Self) -> Ordering {
2326            Ord::cmp(*self, *other)
2327        }
2328    }
2329    #[stable(feature = "rust1", since = "1.0.0")]
2330    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2331    impl<A: PointeeSized> const Eq for &mut A where A: [const] Eq {}
2332
2333    #[stable(feature = "rust1", since = "1.0.0")]
2334    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2335    impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &A
2336    where
2337        A: [const] PartialEq<B>,
2338    {
2339        #[inline]
2340        #[ferrocene::prevalidated]
2341        fn eq(&self, other: &&mut B) -> bool {
2342            PartialEq::eq(*self, *other)
2343        }
2344        #[inline]
2345        #[ferrocene::prevalidated]
2346        fn ne(&self, other: &&mut B) -> bool {
2347            PartialEq::ne(*self, *other)
2348        }
2349    }
2350
2351    #[stable(feature = "rust1", since = "1.0.0")]
2352    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2353    impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &mut A
2354    where
2355        A: [const] PartialEq<B>,
2356    {
2357        #[inline]
2358        #[ferrocene::prevalidated]
2359        fn eq(&self, other: &&B) -> bool {
2360            PartialEq::eq(*self, *other)
2361        }
2362        #[inline]
2363        #[ferrocene::prevalidated]
2364        fn ne(&self, other: &&B) -> bool {
2365            PartialEq::ne(*self, *other)
2366        }
2367    }
2368}