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