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