[go: up one dir, main page]

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