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