]> git.lizzy.rs Git - rust.git/blob - library/core/src/cmp.rs
Rollup merge of #79293 - Havvy:test-eval-order-compound-assign, r=Mark-Simulacrum
[rust.git] / library / core / src / cmp.rs
1 //! Functionality for ordering and comparison.
2 //!
3 //! This module contains various tools for ordering and comparing values. In
4 //! summary:
5 //!
6 //! * [`Eq`] and [`PartialEq`] are traits that allow you to define total and
7 //!   partial equality between values, respectively. Implementing them overloads
8 //!   the `==` and `!=` operators.
9 //! * [`Ord`] and [`PartialOrd`] are traits that allow you to define total and
10 //!   partial orderings between values, respectively. Implementing them overloads
11 //!   the `<`, `<=`, `>`, and `>=` operators.
12 //! * [`Ordering`] is an enum returned by the main functions of [`Ord`] and
13 //!   [`PartialOrd`], and describes an ordering.
14 //! * [`Reverse`] is a struct that allows you to easily reverse an ordering.
15 //! * [`max`] and [`min`] are functions that build off of [`Ord`] and allow you
16 //!   to find the maximum or minimum of two values.
17 //!
18 //! For more details, see the respective documentation of each item in the list.
19 //!
20 //! [`max`]: Ord::max
21 //! [`min`]: Ord::min
22
23 #![stable(feature = "rust1", since = "1.0.0")]
24
25 use self::Ordering::*;
26
27 /// Trait for equality comparisons which are [partial equivalence
28 /// relations](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
29 ///
30 /// This trait allows for partial equality, for types that do not have a full
31 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
32 /// so floating point types implement `PartialEq` but not [`Eq`].
33 ///
34 /// Formally, the equality must be (for all `a`, `b` and `c`):
35 ///
36 /// - symmetric: `a == b` implies `b == a`; and
37 /// - transitive: `a == b` and `b == c` implies `a == c`.
38 ///
39 /// Note that these requirements mean that the trait itself must be implemented
40 /// symmetrically and transitively: if `T: PartialEq<U>` and `U: PartialEq<V>`
41 /// then `U: PartialEq<T>` and `T: PartialEq<V>`.
42 ///
43 /// ## Derivable
44 ///
45 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
46 /// instances are equal if all fields are equal, and not equal if any fields
47 /// are not equal. When `derive`d on enums, each variant is equal to itself
48 /// and not equal to the other variants.
49 ///
50 /// ## How can I implement `PartialEq`?
51 ///
52 /// `PartialEq` only requires the [`eq`] method to be implemented; [`ne`] is defined
53 /// in terms of it by default. Any manual implementation of [`ne`] *must* respect
54 /// the rule that [`eq`] is a strict inverse of [`ne`]; that is, `!(a == b)` if and
55 /// only if `a != b`.
56 ///
57 /// Implementations of `PartialEq`, [`PartialOrd`], and [`Ord`] *must* agree with
58 /// each other. It's easy to accidentally make them disagree by deriving some
59 /// of the traits and manually implementing others.
60 ///
61 /// An example implementation for a domain in which two books are considered
62 /// the same book if their ISBN matches, even if the formats differ:
63 ///
64 /// ```
65 /// enum BookFormat {
66 ///     Paperback,
67 ///     Hardback,
68 ///     Ebook,
69 /// }
70 ///
71 /// struct Book {
72 ///     isbn: i32,
73 ///     format: BookFormat,
74 /// }
75 ///
76 /// impl PartialEq for Book {
77 ///     fn eq(&self, other: &Self) -> bool {
78 ///         self.isbn == other.isbn
79 ///     }
80 /// }
81 ///
82 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
83 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
84 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
85 ///
86 /// assert!(b1 == b2);
87 /// assert!(b1 != b3);
88 /// ```
89 ///
90 /// ## How can I compare two different types?
91 ///
92 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
93 /// For example, let's tweak our previous code a bit:
94 ///
95 /// ```
96 /// // The derive implements <BookFormat> == <BookFormat> comparisons
97 /// #[derive(PartialEq)]
98 /// enum BookFormat {
99 ///     Paperback,
100 ///     Hardback,
101 ///     Ebook,
102 /// }
103 ///
104 /// struct Book {
105 ///     isbn: i32,
106 ///     format: BookFormat,
107 /// }
108 ///
109 /// // Implement <Book> == <BookFormat> comparisons
110 /// impl PartialEq<BookFormat> for Book {
111 ///     fn eq(&self, other: &BookFormat) -> bool {
112 ///         self.format == *other
113 ///     }
114 /// }
115 ///
116 /// // Implement <BookFormat> == <Book> comparisons
117 /// impl PartialEq<Book> for BookFormat {
118 ///     fn eq(&self, other: &Book) -> bool {
119 ///         *self == other.format
120 ///     }
121 /// }
122 ///
123 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
124 ///
125 /// assert!(b1 == BookFormat::Paperback);
126 /// assert!(BookFormat::Ebook != b1);
127 /// ```
128 ///
129 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
130 /// we allow `BookFormat`s to be compared with `Book`s.
131 ///
132 /// A comparison like the one above, which ignores some fields of the struct,
133 /// can be dangerous. It can easily lead to an unintended violation of the
134 /// requirements for a partial equivalence relation. For example, if we kept
135 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
136 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
137 /// via the manual implementation from the first example) then the result would
138 /// violate transitivity:
139 ///
140 /// ```should_panic
141 /// #[derive(PartialEq)]
142 /// enum BookFormat {
143 ///     Paperback,
144 ///     Hardback,
145 ///     Ebook,
146 /// }
147 ///
148 /// #[derive(PartialEq)]
149 /// struct Book {
150 ///     isbn: i32,
151 ///     format: BookFormat,
152 /// }
153 ///
154 /// impl PartialEq<BookFormat> for Book {
155 ///     fn eq(&self, other: &BookFormat) -> bool {
156 ///         self.format == *other
157 ///     }
158 /// }
159 ///
160 /// impl PartialEq<Book> for BookFormat {
161 ///     fn eq(&self, other: &Book) -> bool {
162 ///         *self == other.format
163 ///     }
164 /// }
165 ///
166 /// fn main() {
167 ///     let b1 = Book { isbn: 1, format: BookFormat::Paperback };
168 ///     let b2 = Book { isbn: 2, format: BookFormat::Paperback };
169 ///
170 ///     assert!(b1 == BookFormat::Paperback);
171 ///     assert!(BookFormat::Paperback == b2);
172 ///
173 ///     // The following should hold by transitivity but doesn't.
174 ///     assert!(b1 == b2); // <-- PANICS
175 /// }
176 /// ```
177 ///
178 /// # Examples
179 ///
180 /// ```
181 /// let x: u32 = 0;
182 /// let y: u32 = 1;
183 ///
184 /// assert_eq!(x == y, false);
185 /// assert_eq!(x.eq(&y), false);
186 /// ```
187 ///
188 /// [`eq`]: PartialEq::eq
189 /// [`ne`]: PartialEq::ne
190 #[lang = "eq"]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 #[doc(alias = "==")]
193 #[doc(alias = "!=")]
194 #[rustc_on_unimplemented(
195     message = "can't compare `{Self}` with `{Rhs}`",
196     label = "no implementation for `{Self} == {Rhs}`"
197 )]
198 pub trait PartialEq<Rhs: ?Sized = Self> {
199     /// This method tests for `self` and `other` values to be equal, and is used
200     /// by `==`.
201     #[must_use]
202     #[stable(feature = "rust1", since = "1.0.0")]
203     fn eq(&self, other: &Rhs) -> bool;
204
205     /// This method tests for `!=`.
206     #[inline]
207     #[must_use]
208     #[stable(feature = "rust1", since = "1.0.0")]
209     fn ne(&self, other: &Rhs) -> bool {
210         !self.eq(other)
211     }
212 }
213
214 /// Derive macro generating an impl of the trait `PartialEq`.
215 #[rustc_builtin_macro]
216 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
217 #[allow_internal_unstable(core_intrinsics, structural_match)]
218 pub macro PartialEq($item:item) {
219     /* compiler built-in */
220 }
221
222 /// Trait for equality comparisons which are [equivalence relations](
223 /// https://en.wikipedia.org/wiki/Equivalence_relation).
224 ///
225 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
226 /// be (for all `a`, `b` and `c`):
227 ///
228 /// - reflexive: `a == a`;
229 /// - symmetric: `a == b` implies `b == a`; and
230 /// - transitive: `a == b` and `b == c` implies `a == c`.
231 ///
232 /// This property cannot be checked by the compiler, and therefore `Eq` implies
233 /// [`PartialEq`], and has no extra methods.
234 ///
235 /// ## Derivable
236 ///
237 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
238 /// no extra methods, it is only informing the compiler that this is an
239 /// equivalence relation rather than a partial equivalence relation. Note that
240 /// the `derive` strategy requires all fields are `Eq`, which isn't
241 /// always desired.
242 ///
243 /// ## How can I implement `Eq`?
244 ///
245 /// If you cannot use the `derive` strategy, specify that your type implements
246 /// `Eq`, which has no methods:
247 ///
248 /// ```
249 /// enum BookFormat { Paperback, Hardback, Ebook }
250 /// struct Book {
251 ///     isbn: i32,
252 ///     format: BookFormat,
253 /// }
254 /// impl PartialEq for Book {
255 ///     fn eq(&self, other: &Self) -> bool {
256 ///         self.isbn == other.isbn
257 ///     }
258 /// }
259 /// impl Eq for Book {}
260 /// ```
261 #[doc(alias = "==")]
262 #[doc(alias = "!=")]
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub trait Eq: PartialEq<Self> {
265     // this method is used solely by #[deriving] to assert
266     // that every component of a type implements #[deriving]
267     // itself, the current deriving infrastructure means doing this
268     // assertion without using a method on this trait is nearly
269     // impossible.
270     //
271     // This should never be implemented by hand.
272     #[doc(hidden)]
273     #[inline]
274     #[stable(feature = "rust1", since = "1.0.0")]
275     fn assert_receiver_is_total_eq(&self) {}
276 }
277
278 /// Derive macro generating an impl of the trait `Eq`.
279 #[rustc_builtin_macro]
280 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
281 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match)]
282 pub macro Eq($item:item) {
283     /* compiler built-in */
284 }
285
286 // FIXME: this struct is used solely by #[derive] to
287 // assert that every component of a type implements Eq.
288 //
289 // This struct should never appear in user code.
290 #[doc(hidden)]
291 #[allow(missing_debug_implementations)]
292 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
293 pub struct AssertParamIsEq<T: Eq + ?Sized> {
294     _field: crate::marker::PhantomData<T>,
295 }
296
297 /// An `Ordering` is the result of a comparison between two values.
298 ///
299 /// # Examples
300 ///
301 /// ```
302 /// use std::cmp::Ordering;
303 ///
304 /// let result = 1.cmp(&2);
305 /// assert_eq!(Ordering::Less, result);
306 ///
307 /// let result = 1.cmp(&1);
308 /// assert_eq!(Ordering::Equal, result);
309 ///
310 /// let result = 2.cmp(&1);
311 /// assert_eq!(Ordering::Greater, result);
312 /// ```
313 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub enum Ordering {
316     /// An ordering where a compared value is less than another.
317     #[stable(feature = "rust1", since = "1.0.0")]
318     Less = -1,
319     /// An ordering where a compared value is equal to another.
320     #[stable(feature = "rust1", since = "1.0.0")]
321     Equal = 0,
322     /// An ordering where a compared value is greater than another.
323     #[stable(feature = "rust1", since = "1.0.0")]
324     Greater = 1,
325 }
326
327 impl Ordering {
328     /// Reverses the `Ordering`.
329     ///
330     /// * `Less` becomes `Greater`.
331     /// * `Greater` becomes `Less`.
332     /// * `Equal` becomes `Equal`.
333     ///
334     /// # Examples
335     ///
336     /// Basic behavior:
337     ///
338     /// ```
339     /// use std::cmp::Ordering;
340     ///
341     /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
342     /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
343     /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
344     /// ```
345     ///
346     /// This method can be used to reverse a comparison:
347     ///
348     /// ```
349     /// let data: &mut [_] = &mut [2, 10, 5, 8];
350     ///
351     /// // sort the array from largest to smallest.
352     /// data.sort_by(|a, b| a.cmp(b).reverse());
353     ///
354     /// let b: &mut [_] = &mut [10, 8, 5, 2];
355     /// assert!(data == b);
356     /// ```
357     #[inline]
358     #[must_use]
359     #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
360     #[stable(feature = "rust1", since = "1.0.0")]
361     pub const fn reverse(self) -> Ordering {
362         match self {
363             Less => Greater,
364             Equal => Equal,
365             Greater => Less,
366         }
367     }
368
369     /// Chains two orderings.
370     ///
371     /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
372     ///
373     /// # Examples
374     ///
375     /// ```
376     /// use std::cmp::Ordering;
377     ///
378     /// let result = Ordering::Equal.then(Ordering::Less);
379     /// assert_eq!(result, Ordering::Less);
380     ///
381     /// let result = Ordering::Less.then(Ordering::Equal);
382     /// assert_eq!(result, Ordering::Less);
383     ///
384     /// let result = Ordering::Less.then(Ordering::Greater);
385     /// assert_eq!(result, Ordering::Less);
386     ///
387     /// let result = Ordering::Equal.then(Ordering::Equal);
388     /// assert_eq!(result, Ordering::Equal);
389     ///
390     /// let x: (i64, i64, i64) = (1, 2, 7);
391     /// let y: (i64, i64, i64) = (1, 5, 3);
392     /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
393     ///
394     /// assert_eq!(result, Ordering::Less);
395     /// ```
396     #[inline]
397     #[must_use]
398     #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
399     #[stable(feature = "ordering_chaining", since = "1.17.0")]
400     pub const fn then(self, other: Ordering) -> Ordering {
401         match self {
402             Equal => other,
403             _ => self,
404         }
405     }
406
407     /// Chains the ordering with the given function.
408     ///
409     /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
410     /// the result.
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// use std::cmp::Ordering;
416     ///
417     /// let result = Ordering::Equal.then_with(|| Ordering::Less);
418     /// assert_eq!(result, Ordering::Less);
419     ///
420     /// let result = Ordering::Less.then_with(|| Ordering::Equal);
421     /// assert_eq!(result, Ordering::Less);
422     ///
423     /// let result = Ordering::Less.then_with(|| Ordering::Greater);
424     /// assert_eq!(result, Ordering::Less);
425     ///
426     /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
427     /// assert_eq!(result, Ordering::Equal);
428     ///
429     /// let x: (i64, i64, i64) = (1, 2, 7);
430     /// let y: (i64, i64, i64)  = (1, 5, 3);
431     /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
432     ///
433     /// assert_eq!(result, Ordering::Less);
434     /// ```
435     #[inline]
436     #[must_use]
437     #[stable(feature = "ordering_chaining", since = "1.17.0")]
438     pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
439         match self {
440             Equal => f(),
441             _ => self,
442         }
443     }
444 }
445
446 /// A helper struct for reverse ordering.
447 ///
448 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
449 /// can be used to reverse order a part of a key.
450 ///
451 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
452 ///
453 /// # Examples
454 ///
455 /// ```
456 /// use std::cmp::Reverse;
457 ///
458 /// let mut v = vec![1, 2, 3, 4, 5, 6];
459 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
460 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
461 /// ```
462 #[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
463 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
464 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
465
466 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
467 impl<T: PartialOrd> PartialOrd for Reverse<T> {
468     #[inline]
469     fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
470         other.0.partial_cmp(&self.0)
471     }
472
473     #[inline]
474     fn lt(&self, other: &Self) -> bool {
475         other.0 < self.0
476     }
477     #[inline]
478     fn le(&self, other: &Self) -> bool {
479         other.0 <= self.0
480     }
481     #[inline]
482     fn gt(&self, other: &Self) -> bool {
483         other.0 > self.0
484     }
485     #[inline]
486     fn ge(&self, other: &Self) -> bool {
487         other.0 >= self.0
488     }
489 }
490
491 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
492 impl<T: Ord> Ord for Reverse<T> {
493     #[inline]
494     fn cmp(&self, other: &Reverse<T>) -> Ordering {
495         other.0.cmp(&self.0)
496     }
497 }
498
499 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
500 ///
501 /// An order is a total order if it is (for all `a`, `b` and `c`):
502 ///
503 /// - total and asymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
504 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
505 ///
506 /// ## Derivable
507 ///
508 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
509 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the top-to-bottom declaration order of the struct's members.
510 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
511 ///
512 /// ## Lexicographical comparison
513 ///
514 /// Lexicographical comparison is an operation with the following properties:
515 ///  - Two sequences are compared element by element.
516 ///  - The first mismatching element defines which sequence is lexicographically less or greater than the other.
517 ///  - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
518 ///  - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
519 ///  - An empty sequence is lexicographically less than any non-empty sequence.
520 ///  - Two empty sequences are lexicographically equal.
521 ///
522 /// ## How can I implement `Ord`?
523 ///
524 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
525 ///
526 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
527 /// [`cmp`] on your type's fields.
528 ///
529 /// Implementations of [`PartialEq`], [`PartialOrd`], and `Ord` *must*
530 /// agree with each other. That is, `a.cmp(b) == Ordering::Equal` if
531 /// and only if `a == b` and `Some(a.cmp(b)) == a.partial_cmp(b)` for
532 /// all `a` and `b`. It's easy to accidentally make them disagree by
533 /// deriving some of the traits and manually implementing others.
534 ///
535 /// Here's an example where you want to sort people by height only, disregarding `id`
536 /// and `name`:
537 ///
538 /// ```
539 /// use std::cmp::Ordering;
540 ///
541 /// #[derive(Eq)]
542 /// struct Person {
543 ///     id: u32,
544 ///     name: String,
545 ///     height: u32,
546 /// }
547 ///
548 /// impl Ord for Person {
549 ///     fn cmp(&self, other: &Self) -> Ordering {
550 ///         self.height.cmp(&other.height)
551 ///     }
552 /// }
553 ///
554 /// impl PartialOrd for Person {
555 ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
556 ///         Some(self.cmp(other))
557 ///     }
558 /// }
559 ///
560 /// impl PartialEq for Person {
561 ///     fn eq(&self, other: &Self) -> bool {
562 ///         self.height == other.height
563 ///     }
564 /// }
565 /// ```
566 ///
567 /// [`cmp`]: Ord::cmp
568 #[doc(alias = "<")]
569 #[doc(alias = ">")]
570 #[doc(alias = "<=")]
571 #[doc(alias = ">=")]
572 #[stable(feature = "rust1", since = "1.0.0")]
573 pub trait Ord: Eq + PartialOrd<Self> {
574     /// This method returns an [`Ordering`] between `self` and `other`.
575     ///
576     /// By convention, `self.cmp(&other)` returns the ordering matching the expression
577     /// `self <operator> other` if true.
578     ///
579     /// # Examples
580     ///
581     /// ```
582     /// use std::cmp::Ordering;
583     ///
584     /// assert_eq!(5.cmp(&10), Ordering::Less);
585     /// assert_eq!(10.cmp(&5), Ordering::Greater);
586     /// assert_eq!(5.cmp(&5), Ordering::Equal);
587     /// ```
588     #[must_use]
589     #[stable(feature = "rust1", since = "1.0.0")]
590     fn cmp(&self, other: &Self) -> Ordering;
591
592     /// Compares and returns the maximum of two values.
593     ///
594     /// Returns the second argument if the comparison determines them to be equal.
595     ///
596     /// # Examples
597     ///
598     /// ```
599     /// assert_eq!(2, 1.max(2));
600     /// assert_eq!(2, 2.max(2));
601     /// ```
602     #[stable(feature = "ord_max_min", since = "1.21.0")]
603     #[inline]
604     #[must_use]
605     fn max(self, other: Self) -> Self
606     where
607         Self: Sized,
608     {
609         max_by(self, other, Ord::cmp)
610     }
611
612     /// Compares and returns the minimum of two values.
613     ///
614     /// Returns the first argument if the comparison determines them to be equal.
615     ///
616     /// # Examples
617     ///
618     /// ```
619     /// assert_eq!(1, 1.min(2));
620     /// assert_eq!(2, 2.min(2));
621     /// ```
622     #[stable(feature = "ord_max_min", since = "1.21.0")]
623     #[inline]
624     #[must_use]
625     fn min(self, other: Self) -> Self
626     where
627         Self: Sized,
628     {
629         min_by(self, other, Ord::cmp)
630     }
631
632     /// Restrict a value to a certain interval.
633     ///
634     /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
635     /// less than `min`. Otherwise this returns `self`.
636     ///
637     /// # Panics
638     ///
639     /// Panics if `min > max`.
640     ///
641     /// # Examples
642     ///
643     /// ```
644     /// assert!((-3).clamp(-2, 1) == -2);
645     /// assert!(0.clamp(-2, 1) == 0);
646     /// assert!(2.clamp(-2, 1) == 1);
647     /// ```
648     #[must_use]
649     #[stable(feature = "clamp", since = "1.50.0")]
650     fn clamp(self, min: Self, max: Self) -> Self
651     where
652         Self: Sized,
653     {
654         assert!(min <= max);
655         if self < min {
656             min
657         } else if self > max {
658             max
659         } else {
660             self
661         }
662     }
663 }
664
665 /// Derive macro generating an impl of the trait `Ord`.
666 #[rustc_builtin_macro]
667 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
668 #[allow_internal_unstable(core_intrinsics)]
669 pub macro Ord($item:item) {
670     /* compiler built-in */
671 }
672
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl Eq for Ordering {}
675
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl Ord for Ordering {
678     #[inline]
679     fn cmp(&self, other: &Ordering) -> Ordering {
680         (*self as i32).cmp(&(*other as i32))
681     }
682 }
683
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl PartialOrd for Ordering {
686     #[inline]
687     fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
688         (*self as i32).partial_cmp(&(*other as i32))
689     }
690 }
691
692 /// Trait for values that can be compared for a sort-order.
693 ///
694 /// The comparison must satisfy, for all `a`, `b` and `c`:
695 ///
696 /// - asymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
697 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
698 ///
699 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
700 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
701 /// PartialOrd<V>`.
702 ///
703 /// ## Derivable
704 ///
705 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
706 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
707 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
708 ///
709 /// ## How can I implement `PartialOrd`?
710 ///
711 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
712 /// generated from default implementations.
713 ///
714 /// However it remains possible to implement the others separately for types which do not have a
715 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
716 /// false` (cf. IEEE 754-2008 section 5.11).
717 ///
718 /// `PartialOrd` requires your type to be [`PartialEq`].
719 ///
720 /// Implementations of [`PartialEq`], `PartialOrd`, and [`Ord`] *must* agree with each other. It's
721 /// easy to accidentally make them disagree by deriving some of the traits and manually
722 /// implementing others.
723 ///
724 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
725 ///
726 /// ```
727 /// use std::cmp::Ordering;
728 ///
729 /// #[derive(Eq)]
730 /// struct Person {
731 ///     id: u32,
732 ///     name: String,
733 ///     height: u32,
734 /// }
735 ///
736 /// impl PartialOrd for Person {
737 ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
738 ///         Some(self.cmp(other))
739 ///     }
740 /// }
741 ///
742 /// impl Ord for Person {
743 ///     fn cmp(&self, other: &Self) -> Ordering {
744 ///         self.height.cmp(&other.height)
745 ///     }
746 /// }
747 ///
748 /// impl PartialEq for Person {
749 ///     fn eq(&self, other: &Self) -> bool {
750 ///         self.height == other.height
751 ///     }
752 /// }
753 /// ```
754 ///
755 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
756 /// is an example of `Person` types who have a floating-point `height` field that
757 /// is the only field to be used for sorting:
758 ///
759 /// ```
760 /// use std::cmp::Ordering;
761 ///
762 /// struct Person {
763 ///     id: u32,
764 ///     name: String,
765 ///     height: f64,
766 /// }
767 ///
768 /// impl PartialOrd for Person {
769 ///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
770 ///         self.height.partial_cmp(&other.height)
771 ///     }
772 /// }
773 ///
774 /// impl PartialEq for Person {
775 ///     fn eq(&self, other: &Self) -> bool {
776 ///         self.height == other.height
777 ///     }
778 /// }
779 /// ```
780 ///
781 /// # Examples
782 ///
783 /// ```
784 /// let x : u32 = 0;
785 /// let y : u32 = 1;
786 ///
787 /// assert_eq!(x < y, true);
788 /// assert_eq!(x.lt(&y), true);
789 /// ```
790 ///
791 /// [`partial_cmp`]: PartialOrd::partial_cmp
792 /// [`cmp`]: Ord::cmp
793 #[lang = "partial_ord"]
794 #[stable(feature = "rust1", since = "1.0.0")]
795 #[doc(alias = ">")]
796 #[doc(alias = "<")]
797 #[doc(alias = "<=")]
798 #[doc(alias = ">=")]
799 #[rustc_on_unimplemented(
800     message = "can't compare `{Self}` with `{Rhs}`",
801     label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
802 )]
803 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
804     /// This method returns an ordering between `self` and `other` values if one exists.
805     ///
806     /// # Examples
807     ///
808     /// ```
809     /// use std::cmp::Ordering;
810     ///
811     /// let result = 1.0.partial_cmp(&2.0);
812     /// assert_eq!(result, Some(Ordering::Less));
813     ///
814     /// let result = 1.0.partial_cmp(&1.0);
815     /// assert_eq!(result, Some(Ordering::Equal));
816     ///
817     /// let result = 2.0.partial_cmp(&1.0);
818     /// assert_eq!(result, Some(Ordering::Greater));
819     /// ```
820     ///
821     /// When comparison is impossible:
822     ///
823     /// ```
824     /// let result = f64::NAN.partial_cmp(&1.0);
825     /// assert_eq!(result, None);
826     /// ```
827     #[must_use]
828     #[stable(feature = "rust1", since = "1.0.0")]
829     fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
830
831     /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
832     ///
833     /// # Examples
834     ///
835     /// ```
836     /// let result = 1.0 < 2.0;
837     /// assert_eq!(result, true);
838     ///
839     /// let result = 2.0 < 1.0;
840     /// assert_eq!(result, false);
841     /// ```
842     #[inline]
843     #[must_use]
844     #[stable(feature = "rust1", since = "1.0.0")]
845     fn lt(&self, other: &Rhs) -> bool {
846         matches!(self.partial_cmp(other), Some(Less))
847     }
848
849     /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
850     /// operator.
851     ///
852     /// # Examples
853     ///
854     /// ```
855     /// let result = 1.0 <= 2.0;
856     /// assert_eq!(result, true);
857     ///
858     /// let result = 2.0 <= 2.0;
859     /// assert_eq!(result, true);
860     /// ```
861     #[inline]
862     #[must_use]
863     #[stable(feature = "rust1", since = "1.0.0")]
864     fn le(&self, other: &Rhs) -> bool {
865         matches!(self.partial_cmp(other), Some(Less | Equal))
866     }
867
868     /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
869     ///
870     /// # Examples
871     ///
872     /// ```
873     /// let result = 1.0 > 2.0;
874     /// assert_eq!(result, false);
875     ///
876     /// let result = 2.0 > 2.0;
877     /// assert_eq!(result, false);
878     /// ```
879     #[inline]
880     #[must_use]
881     #[stable(feature = "rust1", since = "1.0.0")]
882     fn gt(&self, other: &Rhs) -> bool {
883         matches!(self.partial_cmp(other), Some(Greater))
884     }
885
886     /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
887     /// operator.
888     ///
889     /// # Examples
890     ///
891     /// ```
892     /// let result = 2.0 >= 1.0;
893     /// assert_eq!(result, true);
894     ///
895     /// let result = 2.0 >= 2.0;
896     /// assert_eq!(result, true);
897     /// ```
898     #[inline]
899     #[must_use]
900     #[stable(feature = "rust1", since = "1.0.0")]
901     fn ge(&self, other: &Rhs) -> bool {
902         matches!(self.partial_cmp(other), Some(Greater | Equal))
903     }
904 }
905
906 /// Derive macro generating an impl of the trait `PartialOrd`.
907 #[rustc_builtin_macro]
908 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
909 #[allow_internal_unstable(core_intrinsics)]
910 pub macro PartialOrd($item:item) {
911     /* compiler built-in */
912 }
913
914 /// Compares and returns the minimum of two values.
915 ///
916 /// Returns the first argument if the comparison determines them to be equal.
917 ///
918 /// Internally uses an alias to [`Ord::min`].
919 ///
920 /// # Examples
921 ///
922 /// ```
923 /// use std::cmp;
924 ///
925 /// assert_eq!(1, cmp::min(1, 2));
926 /// assert_eq!(2, cmp::min(2, 2));
927 /// ```
928 #[inline]
929 #[must_use]
930 #[stable(feature = "rust1", since = "1.0.0")]
931 pub fn min<T: Ord>(v1: T, v2: T) -> T {
932     v1.min(v2)
933 }
934
935 /// Returns the minimum of two values with respect to the specified comparison function.
936 ///
937 /// Returns the first argument if the comparison determines them to be equal.
938 ///
939 /// # Examples
940 ///
941 /// ```
942 /// #![feature(cmp_min_max_by)]
943 ///
944 /// use std::cmp;
945 ///
946 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
947 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
948 /// ```
949 #[inline]
950 #[must_use]
951 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
952 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
953     match compare(&v1, &v2) {
954         Ordering::Less | Ordering::Equal => v1,
955         Ordering::Greater => v2,
956     }
957 }
958
959 /// Returns the element that gives the minimum value from the specified function.
960 ///
961 /// Returns the first argument if the comparison determines them to be equal.
962 ///
963 /// # Examples
964 ///
965 /// ```
966 /// #![feature(cmp_min_max_by)]
967 ///
968 /// use std::cmp;
969 ///
970 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
971 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
972 /// ```
973 #[inline]
974 #[must_use]
975 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
976 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
977     min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
978 }
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 /// Internally uses an alias to [`Ord::max`].
985 ///
986 /// # Examples
987 ///
988 /// ```
989 /// use std::cmp;
990 ///
991 /// assert_eq!(2, cmp::max(1, 2));
992 /// assert_eq!(2, cmp::max(2, 2));
993 /// ```
994 #[inline]
995 #[must_use]
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn max<T: Ord>(v1: T, v2: T) -> T {
998     v1.max(v2)
999 }
1000
1001 /// Returns the maximum of two values with respect to the specified comparison function.
1002 ///
1003 /// Returns the second argument if the comparison determines them to be equal.
1004 ///
1005 /// # Examples
1006 ///
1007 /// ```
1008 /// #![feature(cmp_min_max_by)]
1009 ///
1010 /// use std::cmp;
1011 ///
1012 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1013 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1014 /// ```
1015 #[inline]
1016 #[must_use]
1017 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1018 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1019     match compare(&v1, &v2) {
1020         Ordering::Less | Ordering::Equal => v2,
1021         Ordering::Greater => v1,
1022     }
1023 }
1024
1025 /// Returns the element that gives the maximum value from the specified function.
1026 ///
1027 /// Returns the second argument if the comparison determines them to be equal.
1028 ///
1029 /// # Examples
1030 ///
1031 /// ```
1032 /// #![feature(cmp_min_max_by)]
1033 ///
1034 /// use std::cmp;
1035 ///
1036 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1037 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1038 /// ```
1039 #[inline]
1040 #[must_use]
1041 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1042 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1043     max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1044 }
1045
1046 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1047 mod impls {
1048     use crate::cmp::Ordering::{self, Equal, Greater, Less};
1049     use crate::hint::unreachable_unchecked;
1050
1051     macro_rules! partial_eq_impl {
1052         ($($t:ty)*) => ($(
1053             #[stable(feature = "rust1", since = "1.0.0")]
1054             impl PartialEq for $t {
1055                 #[inline]
1056                 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1057                 #[inline]
1058                 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1059             }
1060         )*)
1061     }
1062
1063     #[stable(feature = "rust1", since = "1.0.0")]
1064     impl PartialEq for () {
1065         #[inline]
1066         fn eq(&self, _other: &()) -> bool {
1067             true
1068         }
1069         #[inline]
1070         fn ne(&self, _other: &()) -> bool {
1071             false
1072         }
1073     }
1074
1075     partial_eq_impl! {
1076         bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1077     }
1078
1079     macro_rules! eq_impl {
1080         ($($t:ty)*) => ($(
1081             #[stable(feature = "rust1", since = "1.0.0")]
1082             impl Eq for $t {}
1083         )*)
1084     }
1085
1086     eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1087
1088     macro_rules! partial_ord_impl {
1089         ($($t:ty)*) => ($(
1090             #[stable(feature = "rust1", since = "1.0.0")]
1091             impl PartialOrd for $t {
1092                 #[inline]
1093                 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1094                     match (self <= other, self >= other) {
1095                         (false, false) => None,
1096                         (false, true) => Some(Greater),
1097                         (true, false) => Some(Less),
1098                         (true, true) => Some(Equal),
1099                     }
1100                 }
1101                 #[inline]
1102                 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1103                 #[inline]
1104                 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1105                 #[inline]
1106                 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1107                 #[inline]
1108                 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1109             }
1110         )*)
1111     }
1112
1113     #[stable(feature = "rust1", since = "1.0.0")]
1114     impl PartialOrd for () {
1115         #[inline]
1116         fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1117             Some(Equal)
1118         }
1119     }
1120
1121     #[stable(feature = "rust1", since = "1.0.0")]
1122     impl PartialOrd for bool {
1123         #[inline]
1124         fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1125             (*self as u8).partial_cmp(&(*other as u8))
1126         }
1127     }
1128
1129     partial_ord_impl! { f32 f64 }
1130
1131     macro_rules! ord_impl {
1132         ($($t:ty)*) => ($(
1133             #[stable(feature = "rust1", since = "1.0.0")]
1134             impl PartialOrd for $t {
1135                 #[inline]
1136                 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1137                     Some(self.cmp(other))
1138                 }
1139                 #[inline]
1140                 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1141                 #[inline]
1142                 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1143                 #[inline]
1144                 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1145                 #[inline]
1146                 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1147             }
1148
1149             #[stable(feature = "rust1", since = "1.0.0")]
1150             impl Ord for $t {
1151                 #[inline]
1152                 fn cmp(&self, other: &$t) -> Ordering {
1153                     // The order here is important to generate more optimal assembly.
1154                     // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1155                     if *self < *other { Less }
1156                     else if *self == *other { Equal }
1157                     else { Greater }
1158                 }
1159             }
1160         )*)
1161     }
1162
1163     #[stable(feature = "rust1", since = "1.0.0")]
1164     impl Ord for () {
1165         #[inline]
1166         fn cmp(&self, _other: &()) -> Ordering {
1167             Equal
1168         }
1169     }
1170
1171     #[stable(feature = "rust1", since = "1.0.0")]
1172     impl Ord for bool {
1173         #[inline]
1174         fn cmp(&self, other: &bool) -> Ordering {
1175             // Casting to i8's and converting the difference to an Ordering generates
1176             // more optimal assembly.
1177             // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1178             match (*self as i8) - (*other as i8) {
1179                 -1 => Less,
1180                 0 => Equal,
1181                 1 => Greater,
1182                 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1183                 _ => unsafe { unreachable_unchecked() },
1184             }
1185         }
1186     }
1187
1188     ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1189
1190     #[unstable(feature = "never_type", issue = "35121")]
1191     impl PartialEq for ! {
1192         fn eq(&self, _: &!) -> bool {
1193             *self
1194         }
1195     }
1196
1197     #[unstable(feature = "never_type", issue = "35121")]
1198     impl Eq for ! {}
1199
1200     #[unstable(feature = "never_type", issue = "35121")]
1201     impl PartialOrd for ! {
1202         fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1203             *self
1204         }
1205     }
1206
1207     #[unstable(feature = "never_type", issue = "35121")]
1208     impl Ord for ! {
1209         fn cmp(&self, _: &!) -> Ordering {
1210             *self
1211         }
1212     }
1213
1214     // & pointers
1215
1216     #[stable(feature = "rust1", since = "1.0.0")]
1217     impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
1218     where
1219         A: PartialEq<B>,
1220     {
1221         #[inline]
1222         fn eq(&self, other: &&B) -> bool {
1223             PartialEq::eq(*self, *other)
1224         }
1225         #[inline]
1226         fn ne(&self, other: &&B) -> bool {
1227             PartialEq::ne(*self, *other)
1228         }
1229     }
1230     #[stable(feature = "rust1", since = "1.0.0")]
1231     impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1232     where
1233         A: PartialOrd<B>,
1234     {
1235         #[inline]
1236         fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1237             PartialOrd::partial_cmp(*self, *other)
1238         }
1239         #[inline]
1240         fn lt(&self, other: &&B) -> bool {
1241             PartialOrd::lt(*self, *other)
1242         }
1243         #[inline]
1244         fn le(&self, other: &&B) -> bool {
1245             PartialOrd::le(*self, *other)
1246         }
1247         #[inline]
1248         fn gt(&self, other: &&B) -> bool {
1249             PartialOrd::gt(*self, *other)
1250         }
1251         #[inline]
1252         fn ge(&self, other: &&B) -> bool {
1253             PartialOrd::ge(*self, *other)
1254         }
1255     }
1256     #[stable(feature = "rust1", since = "1.0.0")]
1257     impl<A: ?Sized> Ord for &A
1258     where
1259         A: Ord,
1260     {
1261         #[inline]
1262         fn cmp(&self, other: &Self) -> Ordering {
1263             Ord::cmp(*self, *other)
1264         }
1265     }
1266     #[stable(feature = "rust1", since = "1.0.0")]
1267     impl<A: ?Sized> Eq for &A where A: Eq {}
1268
1269     // &mut pointers
1270
1271     #[stable(feature = "rust1", since = "1.0.0")]
1272     impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1273     where
1274         A: PartialEq<B>,
1275     {
1276         #[inline]
1277         fn eq(&self, other: &&mut B) -> bool {
1278             PartialEq::eq(*self, *other)
1279         }
1280         #[inline]
1281         fn ne(&self, other: &&mut B) -> bool {
1282             PartialEq::ne(*self, *other)
1283         }
1284     }
1285     #[stable(feature = "rust1", since = "1.0.0")]
1286     impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1287     where
1288         A: PartialOrd<B>,
1289     {
1290         #[inline]
1291         fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1292             PartialOrd::partial_cmp(*self, *other)
1293         }
1294         #[inline]
1295         fn lt(&self, other: &&mut B) -> bool {
1296             PartialOrd::lt(*self, *other)
1297         }
1298         #[inline]
1299         fn le(&self, other: &&mut B) -> bool {
1300             PartialOrd::le(*self, *other)
1301         }
1302         #[inline]
1303         fn gt(&self, other: &&mut B) -> bool {
1304             PartialOrd::gt(*self, *other)
1305         }
1306         #[inline]
1307         fn ge(&self, other: &&mut B) -> bool {
1308             PartialOrd::ge(*self, *other)
1309         }
1310     }
1311     #[stable(feature = "rust1", since = "1.0.0")]
1312     impl<A: ?Sized> Ord for &mut A
1313     where
1314         A: Ord,
1315     {
1316         #[inline]
1317         fn cmp(&self, other: &Self) -> Ordering {
1318             Ord::cmp(*self, *other)
1319         }
1320     }
1321     #[stable(feature = "rust1", since = "1.0.0")]
1322     impl<A: ?Sized> Eq for &mut A where A: Eq {}
1323
1324     #[stable(feature = "rust1", since = "1.0.0")]
1325     impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1326     where
1327         A: PartialEq<B>,
1328     {
1329         #[inline]
1330         fn eq(&self, other: &&mut B) -> bool {
1331             PartialEq::eq(*self, *other)
1332         }
1333         #[inline]
1334         fn ne(&self, other: &&mut B) -> bool {
1335             PartialEq::ne(*self, *other)
1336         }
1337     }
1338
1339     #[stable(feature = "rust1", since = "1.0.0")]
1340     impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1341     where
1342         A: PartialEq<B>,
1343     {
1344         #[inline]
1345         fn eq(&self, other: &&B) -> bool {
1346             PartialEq::eq(*self, *other)
1347         }
1348         #[inline]
1349         fn ne(&self, other: &&B) -> bool {
1350             PartialEq::ne(*self, *other)
1351         }
1352     }
1353 }