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