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