core/
cmp.rs

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

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy