core/
cmp.rs

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