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