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