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