core/
cmp.rs

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