core/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//! * [`PartialEq<Rhs>`] overloads the `==` and `!=` operators. In cases where
7//! `Rhs` (the right hand side's type) is `Self`, this trait corresponds to a
8//! partial equivalence relation.
9//! * [`Eq`] indicates that the overloaded `==` operator corresponds to an
10//! equivalence relation.
11//! * [`Ord`] and [`PartialOrd`] are traits that allow you to define total and
12//! partial orderings between values, respectively. Implementing them overloads
13//! the `<`, `<=`, `>`, and `>=` operators.
14//! * [`Ordering`] is an enum returned by the main functions of [`Ord`] and
15//! [`PartialOrd`], and describes an ordering of two values (less, equal, or
16//! greater).
17//! * [`Reverse`] is a struct that allows you to easily reverse an ordering.
18//! * [`max`] and [`min`] are functions that build off of [`Ord`] and allow you
19//! to find the maximum or minimum of two values.
20//!
21//! For more details, see the respective documentation of each item in the list.
22//!
23//! [`max`]: Ord::max
24//! [`min`]: Ord::min
25
26#![stable(feature = "rust1", since = "1.0.0")]
27
28mod bytewise;
29pub(crate) use bytewise::BytewiseEq;
30
31use self::Ordering::*;
32use crate::marker::{Destruct, PointeeSized};
33use crate::ops::ControlFlow;
34
35/// Trait for comparisons using the equality operator.
36///
37/// Implementing this trait for types provides the `==` and `!=` operators for
38/// those types.
39///
40/// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
41/// We use the easier-to-read infix notation in the remainder of this documentation.
42///
43/// This trait allows for comparisons using the equality operator, for types
44/// that do not have a full equivalence relation. For example, in floating point
45/// numbers `NaN != NaN`, so floating point types implement `PartialEq` but not
46/// [`trait@Eq`]. Formally speaking, when `Rhs == Self`, this trait corresponds
47/// to a [partial equivalence relation].
48///
49/// [partial equivalence relation]: https://en.wikipedia.org/wiki/Partial_equivalence_relation
50///
51/// Implementations must ensure that `eq` and `ne` are consistent with each other:
52///
53/// - `a != b` if and only if `!(a == b)`.
54///
55/// The default implementation of `ne` provides this consistency and is almost
56/// always sufficient. It should not be overridden without very good reason.
57///
58/// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
59/// be consistent with `PartialEq` (see the documentation of those traits for the exact
60/// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
61/// manually implementing others.
62///
63/// The equality relation `==` must satisfy the following conditions
64/// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
65///
66/// - **Symmetry**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
67/// implies `b == a`**; and
68///
69/// - **Transitivity**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
70/// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
71/// This must also work for longer chains, such as when `A: PartialEq<B>`, `B: PartialEq<C>`,
72/// `C: PartialEq<D>`, and `A: PartialEq<D>` all exist.
73///
74/// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
75/// (transitive) impls are not forced to exist, but these requirements apply
76/// whenever they do exist.
77///
78/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
79/// specified, but users of the trait must ensure that such logic errors do *not* result in
80/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
81/// methods.
82///
83/// ## Cross-crate considerations
84///
85/// Upholding the requirements stated above can become tricky when one crate implements `PartialEq`
86/// for a type of another crate (i.e., to allow comparing one of its own types with a type from the
87/// standard library). The recommendation is to never implement this trait for a foreign type. In
88/// other words, such a crate should do `impl PartialEq<ForeignType> for LocalType`, but it should
89/// *not* do `impl PartialEq<LocalType> for ForeignType`.
90///
91/// This avoids the problem of transitive chains that criss-cross crate boundaries: for all local
92/// types `T`, you may assume that no other crate will add `impl`s that allow comparing `T == U`. In
93/// other words, if other crates add `impl`s that allow building longer transitive chains `U1 == ...
94/// == T == V1 == ...`, then all the types that appear to the right of `T` must be types that the
95/// crate defining `T` already knows about. This rules out transitive chains where downstream crates
96/// can add new `impl`s that "stitch together" comparisons of foreign types in ways that violate
97/// transitivity.
98///
99/// Not having such foreign `impl`s also avoids forward compatibility issues where one crate adding
100/// more `PartialEq` implementations can cause build failures in downstream crates.
101///
102/// ## Derivable
103///
104/// This trait can be used with `#[derive]`. When `derive`d on structs, two
105/// instances are equal if all fields are equal, and not equal if any fields
106/// are not equal. When `derive`d on enums, two instances are equal if they
107/// are the same variant and all fields are equal.
108///
109/// ## How can I implement `PartialEq`?
110///
111/// An example implementation for a domain in which two books are considered
112/// the same book if their ISBN matches, even if the formats differ:
113///
114/// ```
115/// enum BookFormat {
116/// Paperback,
117/// Hardback,
118/// Ebook,
119/// }
120///
121/// struct Book {
122/// isbn: i32,
123/// format: BookFormat,
124/// }
125///
126/// impl PartialEq for Book {
127/// fn eq(&self, other: &Self) -> bool {
128/// self.isbn == other.isbn
129/// }
130/// }
131///
132/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
133/// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
134/// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
135///
136/// assert!(b1 == b2);
137/// assert!(b1 != b3);
138/// ```
139///
140/// ## How can I compare two different types?
141///
142/// The type you can compare with is controlled by `PartialEq`'s type parameter.
143/// For example, let's tweak our previous code a bit:
144///
145/// ```
146/// // The derive implements <BookFormat> == <BookFormat> comparisons
147/// #[derive(PartialEq)]
148/// enum BookFormat {
149/// Paperback,
150/// Hardback,
151/// Ebook,
152/// }
153///
154/// struct Book {
155/// isbn: i32,
156/// format: BookFormat,
157/// }
158///
159/// // Implement <Book> == <BookFormat> comparisons
160/// impl PartialEq<BookFormat> for Book {
161/// fn eq(&self, other: &BookFormat) -> bool {
162/// self.format == *other
163/// }
164/// }
165///
166/// // Implement <BookFormat> == <Book> comparisons
167/// impl PartialEq<Book> for BookFormat {
168/// fn eq(&self, other: &Book) -> bool {
169/// *self == other.format
170/// }
171/// }
172///
173/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
174///
175/// assert!(b1 == BookFormat::Paperback);
176/// assert!(BookFormat::Ebook != b1);
177/// ```
178///
179/// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
180/// we allow `BookFormat`s to be compared with `Book`s.
181///
182/// A comparison like the one above, which ignores some fields of the struct,
183/// can be dangerous. It can easily lead to an unintended violation of the
184/// requirements for a partial equivalence relation. For example, if we kept
185/// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
186/// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
187/// via the manual implementation from the first example) then the result would
188/// violate transitivity:
189///
190/// ```should_panic
191/// #[derive(PartialEq)]
192/// enum BookFormat {
193/// Paperback,
194/// Hardback,
195/// Ebook,
196/// }
197///
198/// #[derive(PartialEq)]
199/// struct Book {
200/// isbn: i32,
201/// format: BookFormat,
202/// }
203///
204/// impl PartialEq<BookFormat> for Book {
205/// fn eq(&self, other: &BookFormat) -> bool {
206/// self.format == *other
207/// }
208/// }
209///
210/// impl PartialEq<Book> for BookFormat {
211/// fn eq(&self, other: &Book) -> bool {
212/// *self == other.format
213/// }
214/// }
215///
216/// fn main() {
217/// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
218/// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
219///
220/// assert!(b1 == BookFormat::Paperback);
221/// assert!(BookFormat::Paperback == b2);
222///
223/// // The following should hold by transitivity but doesn't.
224/// assert!(b1 == b2); // <-- PANICS
225/// }
226/// ```
227///
228/// # Examples
229///
230/// ```
231/// let x: u32 = 0;
232/// let y: u32 = 1;
233///
234/// assert_eq!(x == y, false);
235/// assert_eq!(x.eq(&y), false);
236/// ```
237///
238/// [`eq`]: PartialEq::eq
239/// [`ne`]: PartialEq::ne
240#[lang = "eq"]
241#[stable(feature = "rust1", since = "1.0.0")]
242#[doc(alias = "==")]
243#[doc(alias = "!=")]
244#[diagnostic::on_unimplemented(
245 message = "can't compare `{Self}` with `{Rhs}`",
246 label = "no implementation for `{Self} == {Rhs}`"
247)]
248#[rustc_diagnostic_item = "PartialEq"]
249#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
250pub const trait PartialEq<Rhs: PointeeSized = Self>: PointeeSized {
251 /// Equality operator `==`.
252 ///
253 /// Implementation of the "is equal to" operator `==`:
254 /// tests whether its arguments are equal.
255 #[must_use]
256 #[stable(feature = "rust1", since = "1.0.0")]
257 #[rustc_diagnostic_item = "cmp_partialeq_eq"]
258 fn eq(&self, other: &Rhs) -> bool;
259
260 /// Inequality operator `!=`.
261 ///
262 /// Implementation of the "is not equal to" or "is different from" operator `!=`:
263 /// tests whether its arguments are different.
264 ///
265 /// # Default implementation
266 /// The default implementation of the inequality operator simply calls
267 /// the implementation of the equality operator and negates the result.
268 ///
269 /// This default shouldn't be overridden without good reason,
270 /// such as when forwarding to another PartialEq implementation.
271 #[inline]
272 #[must_use]
273 #[stable(feature = "rust1", since = "1.0.0")]
274 #[rustc_diagnostic_item = "cmp_partialeq_ne"]
275 fn ne(&self, other: &Rhs) -> bool {
276 !self.eq(other)
277 }
278}
279
280/// Derive macro generating an impl of the trait [`PartialEq`].
281/// The behavior of this macro is described in detail [here](PartialEq#derivable).
282#[rustc_builtin_macro]
283#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
284#[allow_internal_unstable(core_intrinsics, structural_match)]
285pub macro PartialEq($item:item) {
286 /* compiler built-in */
287}
288
289/// Trait for comparisons corresponding to [equivalence relations](
290/// https://en.wikipedia.org/wiki/Equivalence_relation).
291///
292/// The primary difference to [`PartialEq`] is the additional requirement for reflexivity. A type
293/// that implements [`PartialEq`] guarantees that for all `a`, `b` and `c`:
294///
295/// - symmetric: `a == b` implies `b == a`
296/// - transitive: `a == b` and `b == c` implies `a == c`
297/// - consistent: `a != b` if and only if `!(a == b)`
298///
299/// `Eq`, which builds on top of [`PartialEq`] also implies:
300///
301/// - reflexive: `a == a`
302///
303/// This property cannot be checked by the compiler, and therefore `Eq` is a trait without methods.
304///
305/// Violating this property is a logic error. The behavior resulting from a logic error is not
306/// specified, but users of the trait must ensure that such logic errors do *not* result in
307/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
308/// methods.
309///
310/// Floating point types such as [`f32`] and [`f64`] implement only [`PartialEq`] but *not* `Eq`
311/// because `NaN` != `NaN`.
312///
313/// ## Derivable
314///
315/// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has no extra methods, it
316/// is only informing the compiler that this is an equivalence relation rather than a partial
317/// equivalence relation. Note that the `derive` strategy requires all fields are `Eq`, which isn't
318/// always desired.
319///
320/// ## How can I implement `Eq`?
321///
322/// If you cannot use the `derive` strategy, specify that your type implements `Eq`, which has no
323/// extra methods:
324///
325/// ```
326/// enum BookFormat {
327/// Paperback,
328/// Hardback,
329/// Ebook,
330/// }
331///
332/// struct Book {
333/// isbn: i32,
334/// format: BookFormat,
335/// }
336///
337/// impl PartialEq for Book {
338/// fn eq(&self, other: &Self) -> bool {
339/// self.isbn == other.isbn
340/// }
341/// }
342///
343/// impl Eq for Book {}
344/// ```
345#[doc(alias = "==")]
346#[doc(alias = "!=")]
347#[stable(feature = "rust1", since = "1.0.0")]
348#[rustc_diagnostic_item = "Eq"]
349#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
350pub const trait Eq: [const] PartialEq<Self> + PointeeSized {
351 // This method was used solely by `#[derive(Eq)]` to assert that every component of a
352 // type implements `Eq` itself.
353 //
354 // This should never be implemented by hand.
355 #[doc(hidden)]
356 #[coverage(off)]
357 #[inline]
358 #[stable(feature = "rust1", since = "1.0.0")]
359 #[rustc_diagnostic_item = "assert_receiver_is_total_eq"]
360 #[deprecated(since = "1.95.0", note = "implementation detail of `#[derive(Eq)]`")]
361 fn assert_receiver_is_total_eq(&self) {}
362
363 // FIXME (#152504): this method is used solely by `#[derive(Eq)]` to assert that
364 // every component of a type implements `Eq` itself. It will be removed again soon.
365 #[doc(hidden)]
366 #[coverage(off)]
367 #[unstable(feature = "derive_eq_internals", issue = "none")]
368 fn assert_fields_are_eq(&self) {}
369}
370
371/// Derive macro generating an impl of the trait [`Eq`].
372/// The behavior of this macro is described in detail [here](Eq#derivable).
373#[rustc_builtin_macro]
374#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
375#[allow_internal_unstable(core_intrinsics, derive_eq_internals, structural_match)]
376#[allow_internal_unstable(coverage_attribute)]
377pub macro Eq($item:item) {
378 /* compiler built-in */
379}
380
381// FIXME: this struct is used solely by #[derive] to
382// assert that every component of a type implements Eq.
383//
384// This struct should never appear in user code.
385#[doc(hidden)]
386#[allow(missing_debug_implementations)]
387#[unstable(
388 feature = "derive_eq_internals",
389 reason = "deriving hack, should not be public",
390 issue = "none"
391)]
392pub struct AssertParamIsEq<T: Eq + PointeeSized> {
393 _field: crate::marker::PhantomData<T>,
394}
395
396/// An `Ordering` is the result of a comparison between two values.
397///
398/// # Examples
399///
400/// ```
401/// use std::cmp::Ordering;
402///
403/// assert_eq!(1.cmp(&2), Ordering::Less);
404///
405/// assert_eq!(1.cmp(&1), Ordering::Equal);
406///
407/// assert_eq!(2.cmp(&1), Ordering::Greater);
408/// ```
409#[derive(Copy, Debug, Hash)]
410#[derive_const(Clone, Eq, PartialOrd, Ord, PartialEq)]
411#[stable(feature = "rust1", since = "1.0.0")]
412// This is a lang item only so that `BinOp::Cmp` in MIR can return it.
413// It has no special behavior, but does require that the three variants
414// `Less`/`Equal`/`Greater` remain `-1_i8`/`0_i8`/`+1_i8` respectively.
415#[lang = "Ordering"]
416#[repr(i8)]
417pub enum Ordering {
418 /// An ordering where a compared value is less than another.
419 #[stable(feature = "rust1", since = "1.0.0")]
420 Less = -1,
421 /// An ordering where a compared value is equal to another.
422 #[stable(feature = "rust1", since = "1.0.0")]
423 Equal = 0,
424 /// An ordering where a compared value is greater than another.
425 #[stable(feature = "rust1", since = "1.0.0")]
426 Greater = 1,
427}
428
429impl Ordering {
430 #[inline]
431 const fn as_raw(self) -> i8 {
432 // FIXME(const-hack): just use `PartialOrd` against `Equal` once that's const
433 crate::intrinsics::discriminant_value(&self)
434 }
435
436 /// Returns `true` if the ordering is the `Equal` variant.
437 ///
438 /// # Examples
439 ///
440 /// ```
441 /// use std::cmp::Ordering;
442 ///
443 /// assert_eq!(Ordering::Less.is_eq(), false);
444 /// assert_eq!(Ordering::Equal.is_eq(), true);
445 /// assert_eq!(Ordering::Greater.is_eq(), false);
446 /// ```
447 #[inline]
448 #[must_use]
449 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
450 #[stable(feature = "ordering_helpers", since = "1.53.0")]
451 pub const fn is_eq(self) -> bool {
452 // All the `is_*` methods are implemented as comparisons against zero
453 // to follow how clang's libcxx implements their equivalents in
454 // <https://github.com/llvm/llvm-project/blob/60486292b79885b7800b082754153202bef5b1f0/libcxx/include/__compare/is_eq.h#L23-L28>
455
456 self.as_raw() == 0
457 }
458
459 /// Returns `true` if the ordering is not the `Equal` variant.
460 ///
461 /// # Examples
462 ///
463 /// ```
464 /// use std::cmp::Ordering;
465 ///
466 /// assert_eq!(Ordering::Less.is_ne(), true);
467 /// assert_eq!(Ordering::Equal.is_ne(), false);
468 /// assert_eq!(Ordering::Greater.is_ne(), true);
469 /// ```
470 #[inline]
471 #[must_use]
472 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
473 #[stable(feature = "ordering_helpers", since = "1.53.0")]
474 pub const fn is_ne(self) -> bool {
475 self.as_raw() != 0
476 }
477
478 /// Returns `true` if the ordering is the `Less` variant.
479 ///
480 /// # Examples
481 ///
482 /// ```
483 /// use std::cmp::Ordering;
484 ///
485 /// assert_eq!(Ordering::Less.is_lt(), true);
486 /// assert_eq!(Ordering::Equal.is_lt(), false);
487 /// assert_eq!(Ordering::Greater.is_lt(), false);
488 /// ```
489 #[inline]
490 #[must_use]
491 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
492 #[stable(feature = "ordering_helpers", since = "1.53.0")]
493 pub const fn is_lt(self) -> bool {
494 self.as_raw() < 0
495 }
496
497 /// Returns `true` if the ordering is the `Greater` variant.
498 ///
499 /// # Examples
500 ///
501 /// ```
502 /// use std::cmp::Ordering;
503 ///
504 /// assert_eq!(Ordering::Less.is_gt(), false);
505 /// assert_eq!(Ordering::Equal.is_gt(), false);
506 /// assert_eq!(Ordering::Greater.is_gt(), true);
507 /// ```
508 #[inline]
509 #[must_use]
510 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
511 #[stable(feature = "ordering_helpers", since = "1.53.0")]
512 pub const fn is_gt(self) -> bool {
513 self.as_raw() > 0
514 }
515
516 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// use std::cmp::Ordering;
522 ///
523 /// assert_eq!(Ordering::Less.is_le(), true);
524 /// assert_eq!(Ordering::Equal.is_le(), true);
525 /// assert_eq!(Ordering::Greater.is_le(), false);
526 /// ```
527 #[inline]
528 #[must_use]
529 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
530 #[stable(feature = "ordering_helpers", since = "1.53.0")]
531 pub const fn is_le(self) -> bool {
532 self.as_raw() <= 0
533 }
534
535 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
536 ///
537 /// # Examples
538 ///
539 /// ```
540 /// use std::cmp::Ordering;
541 ///
542 /// assert_eq!(Ordering::Less.is_ge(), false);
543 /// assert_eq!(Ordering::Equal.is_ge(), true);
544 /// assert_eq!(Ordering::Greater.is_ge(), true);
545 /// ```
546 #[inline]
547 #[must_use]
548 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
549 #[stable(feature = "ordering_helpers", since = "1.53.0")]
550 pub const fn is_ge(self) -> bool {
551 self.as_raw() >= 0
552 }
553
554 /// Reverses the `Ordering`.
555 ///
556 /// * `Less` becomes `Greater`.
557 /// * `Greater` becomes `Less`.
558 /// * `Equal` becomes `Equal`.
559 ///
560 /// # Examples
561 ///
562 /// Basic behavior:
563 ///
564 /// ```
565 /// use std::cmp::Ordering;
566 ///
567 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
568 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
569 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
570 /// ```
571 ///
572 /// This method can be used to reverse a comparison:
573 ///
574 /// ```
575 /// let data: &mut [_] = &mut [2, 10, 5, 8];
576 ///
577 /// // sort the array from largest to smallest.
578 /// data.sort_by(|a, b| a.cmp(b).reverse());
579 ///
580 /// let b: &mut [_] = &mut [10, 8, 5, 2];
581 /// assert!(data == b);
582 /// ```
583 #[inline]
584 #[must_use]
585 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub const fn reverse(self) -> Ordering {
588 match self {
589 Less => Greater,
590 Equal => Equal,
591 Greater => Less,
592 }
593 }
594
595 /// Chains two orderings.
596 ///
597 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
598 ///
599 /// # Examples
600 ///
601 /// ```
602 /// use std::cmp::Ordering;
603 ///
604 /// let result = Ordering::Equal.then(Ordering::Less);
605 /// assert_eq!(result, Ordering::Less);
606 ///
607 /// let result = Ordering::Less.then(Ordering::Equal);
608 /// assert_eq!(result, Ordering::Less);
609 ///
610 /// let result = Ordering::Less.then(Ordering::Greater);
611 /// assert_eq!(result, Ordering::Less);
612 ///
613 /// let result = Ordering::Equal.then(Ordering::Equal);
614 /// assert_eq!(result, Ordering::Equal);
615 ///
616 /// let x: (i64, i64, i64) = (1, 2, 7);
617 /// let y: (i64, i64, i64) = (1, 5, 3);
618 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
619 ///
620 /// assert_eq!(result, Ordering::Less);
621 /// ```
622 #[inline]
623 #[must_use]
624 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
625 #[stable(feature = "ordering_chaining", since = "1.17.0")]
626 pub const fn then(self, other: Ordering) -> Ordering {
627 match self {
628 Equal => other,
629 _ => self,
630 }
631 }
632
633 /// Chains the ordering with the given function.
634 ///
635 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
636 /// the result.
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// use std::cmp::Ordering;
642 ///
643 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
644 /// assert_eq!(result, Ordering::Less);
645 ///
646 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
647 /// assert_eq!(result, Ordering::Less);
648 ///
649 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
650 /// assert_eq!(result, Ordering::Less);
651 ///
652 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
653 /// assert_eq!(result, Ordering::Equal);
654 ///
655 /// let x: (i64, i64, i64) = (1, 2, 7);
656 /// let y: (i64, i64, i64) = (1, 5, 3);
657 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
658 ///
659 /// assert_eq!(result, Ordering::Less);
660 /// ```
661 #[inline]
662 #[must_use]
663 #[stable(feature = "ordering_chaining", since = "1.17.0")]
664 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
665 pub const fn then_with<F>(self, f: F) -> Ordering
666 where
667 F: [const] FnOnce() -> Ordering + [const] Destruct,
668 {
669 match self {
670 Equal => f(),
671 _ => self,
672 }
673 }
674}
675
676/// A helper struct for reverse ordering.
677///
678/// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
679/// can be used to reverse order a part of a key.
680///
681/// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
682///
683/// # Examples
684///
685/// ```
686/// use std::cmp::Reverse;
687///
688/// let mut v = vec![1, 2, 3, 4, 5, 6];
689/// v.sort_by_key(|&num| (num > 3, Reverse(num)));
690/// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
691/// ```
692#[derive(Copy, Debug, Hash)]
693#[derive_const(PartialEq, Eq, Default)]
694#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
695#[repr(transparent)]
696pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
697
698#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
699#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
700const impl<T: [const] PartialOrd> PartialOrd for Reverse<T> {
701 #[inline]
702 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
703 other.0.partial_cmp(&self.0)
704 }
705
706 #[inline]
707 fn lt(&self, other: &Self) -> bool {
708 other.0 < self.0
709 }
710 #[inline]
711 fn le(&self, other: &Self) -> bool {
712 other.0 <= self.0
713 }
714 #[inline]
715 fn gt(&self, other: &Self) -> bool {
716 other.0 > self.0
717 }
718 #[inline]
719 fn ge(&self, other: &Self) -> bool {
720 other.0 >= self.0
721 }
722}
723
724#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
725#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
726const impl<T: [const] Ord> Ord for Reverse<T> {
727 #[inline]
728 fn cmp(&self, other: &Reverse<T>) -> Ordering {
729 other.0.cmp(&self.0)
730 }
731}
732
733#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
734impl<T: Clone> Clone for Reverse<T> {
735 #[inline]
736 fn clone(&self) -> Reverse<T> {
737 Reverse(self.0.clone())
738 }
739
740 #[inline]
741 fn clone_from(&mut self, source: &Self) {
742 self.0.clone_from(&source.0)
743 }
744}
745
746/// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
747///
748/// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure `max`,
749/// `min`, and `clamp` are consistent with `cmp`:
750///
751/// - `partial_cmp(a, b) == Some(cmp(a, b))`.
752/// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
753/// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
754/// - For `a.clamp(min, max)`, see the [method docs](#method.clamp) (ensured by the default
755/// implementation).
756///
757/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
758/// specified, but users of the trait must ensure that such logic errors do *not* result in
759/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
760/// methods.
761///
762/// ## Corollaries
763///
764/// From the above and the requirements of `PartialOrd`, it follows that for all `a`, `b` and `c`:
765///
766/// - exactly one of `a < b`, `a == b` or `a > b` is true; and
767/// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and
768/// `>`.
769///
770/// Mathematically speaking, the `<` operator defines a strict [weak order]. In cases where `==`
771/// conforms to mathematical equality, it also defines a strict [total order].
772///
773/// [weak order]: https://en.wikipedia.org/wiki/Weak_ordering
774/// [total order]: https://en.wikipedia.org/wiki/Total_order
775///
776/// ## Derivable
777///
778/// This trait can be used with `#[derive]`.
779///
780/// When `derive`d on structs, it will produce a
781/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the
782/// top-to-bottom declaration order of the struct's members.
783///
784/// When `derive`d on enums, variants are ordered primarily by their discriminants. Secondarily,
785/// they are ordered by their fields. By default, the discriminant is smallest for variants at the
786/// top, and largest for variants at the bottom. Here's an example:
787///
788/// ```
789/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
790/// enum E {
791/// Top,
792/// Bottom,
793/// }
794///
795/// assert!(E::Top < E::Bottom);
796/// ```
797///
798/// However, manually setting the discriminants can override this default behavior:
799///
800/// ```
801/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
802/// enum E {
803/// Top = 2,
804/// Bottom = 1,
805/// }
806///
807/// assert!(E::Bottom < E::Top);
808/// ```
809///
810/// ## Lexicographical comparison
811///
812/// Lexicographical comparison is an operation with the following properties:
813/// - Two sequences are compared element by element.
814/// - The first mismatching element defines which sequence is lexicographically less or greater
815/// than the other.
816/// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than
817/// the other.
818/// - If two sequences have equivalent elements and are of the same length, then the sequences are
819/// lexicographically equal.
820/// - An empty sequence is lexicographically less than any non-empty sequence.
821/// - Two empty sequences are lexicographically equal.
822///
823/// ## How can I implement `Ord`?
824///
825/// `Ord` requires that the type also be [`PartialOrd`], [`PartialEq`], and [`Eq`].
826///
827/// Because `Ord` implies a stronger ordering relationship than [`PartialOrd`], and both `Ord` and
828/// [`PartialOrd`] must agree, you must choose how to implement `Ord` **first**. You can choose to
829/// derive it, or implement it manually. If you derive it, you should derive all four traits. If you
830/// implement it manually, you should manually implement all four traits, based on the
831/// implementation of `Ord`.
832///
833/// Here's an example where you want to define the `Character` comparison by `health` and
834/// `experience` only, disregarding the field `mana`:
835///
836/// ```
837/// use std::cmp::Ordering;
838///
839/// struct Character {
840/// health: u32,
841/// experience: u32,
842/// mana: f32,
843/// }
844///
845/// impl Ord for Character {
846/// fn cmp(&self, other: &Self) -> Ordering {
847/// self.experience
848/// .cmp(&other.experience)
849/// .then(self.health.cmp(&other.health))
850/// }
851/// }
852///
853/// impl PartialOrd for Character {
854/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
855/// Some(self.cmp(other))
856/// }
857/// }
858///
859/// impl PartialEq for Character {
860/// fn eq(&self, other: &Self) -> bool {
861/// self.health == other.health && self.experience == other.experience
862/// }
863/// }
864///
865/// impl Eq for Character {}
866/// ```
867///
868/// If all you need is to `slice::sort` a type by a field value, it can be simpler to use
869/// `slice::sort_by_key`.
870///
871/// ## Examples of incorrect `Ord` implementations
872///
873/// ```
874/// use std::cmp::Ordering;
875///
876/// #[derive(Debug)]
877/// struct Character {
878/// health: f32,
879/// }
880///
881/// impl Ord for Character {
882/// fn cmp(&self, other: &Self) -> std::cmp::Ordering {
883/// if self.health < other.health {
884/// Ordering::Less
885/// } else if self.health > other.health {
886/// Ordering::Greater
887/// } else {
888/// Ordering::Equal
889/// }
890/// }
891/// }
892///
893/// impl PartialOrd for Character {
894/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
895/// Some(self.cmp(other))
896/// }
897/// }
898///
899/// impl PartialEq for Character {
900/// fn eq(&self, other: &Self) -> bool {
901/// self.health == other.health
902/// }
903/// }
904///
905/// impl Eq for Character {}
906///
907/// let a = Character { health: 4.5 };
908/// let b = Character { health: f32::NAN };
909///
910/// // Mistake: floating-point values do not form a total order and using the built-in comparison
911/// // operands to implement `Ord` irregardless of that reality does not change it. Use
912/// // `f32::total_cmp` if you need a total order for floating-point values.
913///
914/// // Reflexivity requirement of `Ord` is not given.
915/// assert!(a == a);
916/// assert!(b != b);
917///
918/// // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be
919/// // true, not both or neither.
920/// assert_eq!((a < b) as u8 + (b < a) as u8, 0);
921/// ```
922///
923/// ```
924/// use std::cmp::Ordering;
925///
926/// #[derive(Debug)]
927/// struct Character {
928/// health: u32,
929/// experience: u32,
930/// }
931///
932/// impl PartialOrd for Character {
933/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
934/// Some(self.cmp(other))
935/// }
936/// }
937///
938/// impl Ord for Character {
939/// fn cmp(&self, other: &Self) -> std::cmp::Ordering {
940/// if self.health < 50 {
941/// self.health.cmp(&other.health)
942/// } else {
943/// self.experience.cmp(&other.experience)
944/// }
945/// }
946/// }
947///
948/// // For performance reasons implementing `PartialEq` this way is not the idiomatic way, but it
949/// // ensures consistent behavior between `PartialEq`, `PartialOrd` and `Ord` in this example.
950/// impl PartialEq for Character {
951/// fn eq(&self, other: &Self) -> bool {
952/// self.cmp(other) == Ordering::Equal
953/// }
954/// }
955///
956/// impl Eq for Character {}
957///
958/// let a = Character {
959/// health: 3,
960/// experience: 5,
961/// };
962/// let b = Character {
963/// health: 10,
964/// experience: 77,
965/// };
966/// let c = Character {
967/// health: 143,
968/// experience: 2,
969/// };
970///
971/// // Mistake: The implementation of `Ord` compares different fields depending on the value of
972/// // `self.health`, the resulting order is not total.
973///
974/// // Transitivity requirement of `Ord` is not given. If a is smaller than b and b is smaller than
975/// // c, by transitive property a must also be smaller than c.
976/// assert!(a < b && b < c && c < a);
977///
978/// // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be
979/// // true, not both or neither.
980/// assert_eq!((a < c) as u8 + (c < a) as u8, 2);
981/// ```
982///
983/// The documentation of [`PartialOrd`] contains further examples, for example it's wrong for
984/// [`PartialOrd`] and [`PartialEq`] to disagree.
985///
986/// [`cmp`]: Ord::cmp
987#[doc(alias = "<")]
988#[doc(alias = ">")]
989#[doc(alias = "<=")]
990#[doc(alias = ">=")]
991#[stable(feature = "rust1", since = "1.0.0")]
992#[rustc_diagnostic_item = "Ord"]
993#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
994pub const trait Ord: [const] Eq + [const] PartialOrd<Self> + PointeeSized {
995 /// This method returns an [`Ordering`] between `self` and `other`.
996 ///
997 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
998 /// `self <operator> other` if true.
999 ///
1000 /// # Examples
1001 ///
1002 /// ```
1003 /// use std::cmp::Ordering;
1004 ///
1005 /// assert_eq!(5.cmp(&10), Ordering::Less);
1006 /// assert_eq!(10.cmp(&5), Ordering::Greater);
1007 /// assert_eq!(5.cmp(&5), Ordering::Equal);
1008 /// ```
1009 #[must_use]
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 #[rustc_diagnostic_item = "ord_cmp_method"]
1012 fn cmp(&self, other: &Self) -> Ordering;
1013
1014 /// Compares and returns the maximum of two values.
1015 ///
1016 /// Returns the second argument if the comparison determines them to be equal.
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```
1021 /// assert_eq!(1.max(2), 2);
1022 /// assert_eq!(2.max(2), 2);
1023 /// ```
1024 /// ```
1025 /// use std::cmp::Ordering;
1026 ///
1027 /// #[derive(Eq)]
1028 /// struct Equal(&'static str);
1029 ///
1030 /// impl PartialEq for Equal {
1031 /// fn eq(&self, other: &Self) -> bool { true }
1032 /// }
1033 /// impl PartialOrd for Equal {
1034 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1035 /// }
1036 /// impl Ord for Equal {
1037 /// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1038 /// }
1039 ///
1040 /// assert_eq!(Equal("self").max(Equal("other")).0, "other");
1041 /// ```
1042 #[stable(feature = "ord_max_min", since = "1.21.0")]
1043 #[inline]
1044 #[must_use]
1045 #[rustc_diagnostic_item = "cmp_ord_max"]
1046 fn max(self, other: Self) -> Self
1047 where
1048 Self: Sized + [const] Destruct,
1049 {
1050 if other < self { self } else { other }
1051 }
1052
1053 /// Compares and returns the minimum of two values.
1054 ///
1055 /// Returns the first argument if the comparison determines them to be equal.
1056 ///
1057 /// # Examples
1058 ///
1059 /// ```
1060 /// assert_eq!(1.min(2), 1);
1061 /// assert_eq!(2.min(2), 2);
1062 /// ```
1063 /// ```
1064 /// use std::cmp::Ordering;
1065 ///
1066 /// #[derive(Eq)]
1067 /// struct Equal(&'static str);
1068 ///
1069 /// impl PartialEq for Equal {
1070 /// fn eq(&self, other: &Self) -> bool { true }
1071 /// }
1072 /// impl PartialOrd for Equal {
1073 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1074 /// }
1075 /// impl Ord for Equal {
1076 /// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1077 /// }
1078 ///
1079 /// assert_eq!(Equal("self").min(Equal("other")).0, "self");
1080 /// ```
1081 #[stable(feature = "ord_max_min", since = "1.21.0")]
1082 #[inline]
1083 #[must_use]
1084 #[rustc_diagnostic_item = "cmp_ord_min"]
1085 fn min(self, other: Self) -> Self
1086 where
1087 Self: Sized + [const] Destruct,
1088 {
1089 if other < self { other } else { self }
1090 }
1091
1092 /// Restrict a value to a certain interval.
1093 ///
1094 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1095 /// less than `min`. Otherwise this returns `self`.
1096 ///
1097 /// # Panics
1098 ///
1099 /// Panics if `min > max`.
1100 ///
1101 /// # Examples
1102 ///
1103 /// ```
1104 /// assert_eq!((-3).clamp(-2, 1), -2);
1105 /// assert_eq!(0.clamp(-2, 1), 0);
1106 /// assert_eq!(2.clamp(-2, 1), 1);
1107 /// ```
1108 #[must_use]
1109 #[inline]
1110 #[stable(feature = "clamp", since = "1.50.0")]
1111 fn clamp(self, min: Self, max: Self) -> Self
1112 where
1113 Self: Sized + [const] Destruct,
1114 {
1115 assert!(min <= max);
1116 if self < min {
1117 min
1118 } else if self > max {
1119 max
1120 } else {
1121 self
1122 }
1123 }
1124}
1125
1126/// Derive macro generating an impl of the trait [`Ord`].
1127/// The behavior of this macro is described in detail [here](Ord#derivable).
1128#[rustc_builtin_macro]
1129#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1130#[allow_internal_unstable(core_intrinsics)]
1131pub macro Ord($item:item) {
1132 /* compiler built-in */
1133}
1134
1135/// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
1136///
1137/// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using the `<`, `<=`, `>`, and
1138/// `>=` operators, respectively.
1139///
1140/// This trait should **only** contain the comparison logic for a type **if one plans on only
1141/// implementing `PartialOrd` but not [`Ord`]**. Otherwise the comparison logic should be in [`Ord`]
1142/// and this trait implemented with `Some(self.cmp(other))`.
1143///
1144/// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
1145/// The following conditions must hold:
1146///
1147/// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
1148/// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
1149/// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
1150/// 4. `a <= b` if and only if `a < b || a == b`
1151/// 5. `a >= b` if and only if `a > b || a == b`
1152/// 6. `a != b` if and only if `!(a == b)`.
1153///
1154/// Conditions 2–5 above are ensured by the default implementation. Condition 6 is already ensured
1155/// by [`PartialEq`].
1156///
1157/// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
1158/// `partial_cmp` (see the documentation of that trait for the exact requirements). It's easy to
1159/// accidentally make them disagree by deriving some of the traits and manually implementing others.
1160///
1161/// The comparison relations must satisfy the following conditions (for all `a`, `b`, `c` of type
1162/// `A`, `B`, `C`):
1163///
1164/// - **Transitivity**: if `A: PartialOrd<B>` and `B: PartialOrd<C>` and `A: PartialOrd<C>`, then `a
1165/// < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. This must also
1166/// work for longer chains, such as when `A: PartialOrd<B>`, `B: PartialOrd<C>`, `C:
1167/// PartialOrd<D>`, and `A: PartialOrd<D>` all exist.
1168/// - **Duality**: if `A: PartialOrd<B>` and `B: PartialOrd<A>`, then `a < b` if and only if `b >
1169/// a`.
1170///
1171/// Note that the `B: PartialOrd<A>` (dual) and `A: PartialOrd<C>` (transitive) impls are not forced
1172/// to exist, but these requirements apply whenever they do exist.
1173///
1174/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
1175/// specified, but users of the trait must ensure that such logic errors do *not* result in
1176/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
1177/// methods.
1178///
1179/// ## Cross-crate considerations
1180///
1181/// Upholding the requirements stated above can become tricky when one crate implements `PartialOrd`
1182/// for a type of another crate (i.e., to allow comparing one of its own types with a type from the
1183/// standard library). The recommendation is to never implement this trait for a foreign type. In
1184/// other words, such a crate should do `impl PartialOrd<ForeignType> for LocalType`, but it should
1185/// *not* do `impl PartialOrd<LocalType> for ForeignType`.
1186///
1187/// This avoids the problem of transitive chains that criss-cross crate boundaries: for all local
1188/// types `T`, you may assume that no other crate will add `impl`s that allow comparing `T < U`. In
1189/// other words, if other crates add `impl`s that allow building longer transitive chains `U1 < ...
1190/// < T < V1 < ...`, then all the types that appear to the right of `T` must be types that the crate
1191/// defining `T` already knows about. This rules out transitive chains where downstream crates can
1192/// add new `impl`s that "stitch together" comparisons of foreign types in ways that violate
1193/// transitivity.
1194///
1195/// Not having such foreign `impl`s also avoids forward compatibility issues where one crate adding
1196/// more `PartialOrd` implementations can cause build failures in downstream crates.
1197///
1198/// ## Corollaries
1199///
1200/// The following corollaries follow from the above requirements:
1201///
1202/// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
1203/// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
1204/// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
1205///
1206/// ## Strict and non-strict partial orders
1207///
1208/// The `<` and `>` operators behave according to a *strict* partial order. However, `<=` and `>=`
1209/// do **not** behave according to a *non-strict* partial order. That is because mathematically, a
1210/// non-strict partial order would require reflexivity, i.e. `a <= a` would need to be true for
1211/// every `a`. This isn't always the case for types that implement `PartialOrd`, for example:
1212///
1213/// ```
1214/// let a = f64::NAN;
1215/// assert_eq!(a <= a, false);
1216/// ```
1217///
1218/// ## Derivable
1219///
1220/// This trait can be used with `#[derive]`.
1221///
1222/// When `derive`d on structs, it will produce a
1223/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the
1224/// top-to-bottom declaration order of the struct's members.
1225///
1226/// When `derive`d on enums, variants are primarily ordered by their discriminants. Secondarily,
1227/// they are ordered by their fields. By default, the discriminant is smallest for variants at the
1228/// top, and largest for variants at the bottom. Here's an example:
1229///
1230/// ```
1231/// #[derive(PartialEq, PartialOrd)]
1232/// enum E {
1233/// Top,
1234/// Bottom,
1235/// }
1236///
1237/// assert!(E::Top < E::Bottom);
1238/// ```
1239///
1240/// However, manually setting the discriminants can override this default behavior:
1241///
1242/// ```
1243/// #[derive(PartialEq, PartialOrd)]
1244/// enum E {
1245/// Top = 2,
1246/// Bottom = 1,
1247/// }
1248///
1249/// assert!(E::Bottom < E::Top);
1250/// ```
1251///
1252/// ## How can I implement `PartialOrd`?
1253///
1254/// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
1255/// generated from default implementations.
1256///
1257/// However it remains possible to implement the others separately for types which do not have a
1258/// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 == false`
1259/// (cf. IEEE 754-2008 section 5.11).
1260///
1261/// `PartialOrd` requires your type to be [`PartialEq`].
1262///
1263/// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
1264///
1265/// ```
1266/// use std::cmp::Ordering;
1267///
1268/// struct Person {
1269/// id: u32,
1270/// name: String,
1271/// height: u32,
1272/// }
1273///
1274/// impl PartialOrd for Person {
1275/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1276/// Some(self.cmp(other))
1277/// }
1278/// }
1279///
1280/// impl Ord for Person {
1281/// fn cmp(&self, other: &Self) -> Ordering {
1282/// self.height.cmp(&other.height)
1283/// }
1284/// }
1285///
1286/// impl PartialEq for Person {
1287/// fn eq(&self, other: &Self) -> bool {
1288/// self.height == other.height
1289/// }
1290/// }
1291///
1292/// impl Eq for Person {}
1293/// ```
1294///
1295/// You may also find it useful to use [`partial_cmp`] on your type's fields. Here is an example of
1296/// `Person` types who have a floating-point `height` field that is the only field to be used for
1297/// sorting:
1298///
1299/// ```
1300/// use std::cmp::Ordering;
1301///
1302/// struct Person {
1303/// id: u32,
1304/// name: String,
1305/// height: f64,
1306/// }
1307///
1308/// impl PartialOrd for Person {
1309/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1310/// self.height.partial_cmp(&other.height)
1311/// }
1312/// }
1313///
1314/// impl PartialEq for Person {
1315/// fn eq(&self, other: &Self) -> bool {
1316/// self.height == other.height
1317/// }
1318/// }
1319/// ```
1320///
1321/// ## Examples of incorrect `PartialOrd` implementations
1322///
1323/// ```
1324/// use std::cmp::Ordering;
1325///
1326/// #[derive(PartialEq, Debug)]
1327/// struct Character {
1328/// health: u32,
1329/// experience: u32,
1330/// }
1331///
1332/// impl PartialOrd for Character {
1333/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1334/// Some(self.health.cmp(&other.health))
1335/// }
1336/// }
1337///
1338/// let a = Character {
1339/// health: 10,
1340/// experience: 5,
1341/// };
1342/// let b = Character {
1343/// health: 10,
1344/// experience: 77,
1345/// };
1346///
1347/// // Mistake: `PartialEq` and `PartialOrd` disagree with each other.
1348///
1349/// assert_eq!(a.partial_cmp(&b).unwrap(), Ordering::Equal); // a == b according to `PartialOrd`.
1350/// assert_ne!(a, b); // a != b according to `PartialEq`.
1351/// ```
1352///
1353/// # Examples
1354///
1355/// ```
1356/// let x: u32 = 0;
1357/// let y: u32 = 1;
1358///
1359/// assert_eq!(x < y, true);
1360/// assert_eq!(x.lt(&y), true);
1361/// ```
1362///
1363/// [`partial_cmp`]: PartialOrd::partial_cmp
1364/// [`cmp`]: Ord::cmp
1365#[lang = "partial_ord"]
1366#[stable(feature = "rust1", since = "1.0.0")]
1367#[doc(alias = ">")]
1368#[doc(alias = "<")]
1369#[doc(alias = "<=")]
1370#[doc(alias = ">=")]
1371#[diagnostic::on_unimplemented(
1372 message = "can't compare `{Self}` with `{Rhs}`",
1373 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
1374)]
1375#[rustc_diagnostic_item = "PartialOrd"]
1376#[allow(multiple_supertrait_upcastable)] // FIXME(sized_hierarchy): remove this
1377#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1378pub const trait PartialOrd<Rhs: PointeeSized = Self>:
1379 [const] PartialEq<Rhs> + PointeeSized
1380{
1381 /// This method returns an ordering between `self` and `other` values if one exists.
1382 ///
1383 /// # Examples
1384 ///
1385 /// ```
1386 /// use std::cmp::Ordering;
1387 ///
1388 /// let result = 1.0.partial_cmp(&2.0);
1389 /// assert_eq!(result, Some(Ordering::Less));
1390 ///
1391 /// let result = 1.0.partial_cmp(&1.0);
1392 /// assert_eq!(result, Some(Ordering::Equal));
1393 ///
1394 /// let result = 2.0.partial_cmp(&1.0);
1395 /// assert_eq!(result, Some(Ordering::Greater));
1396 /// ```
1397 ///
1398 /// When comparison is impossible:
1399 ///
1400 /// ```
1401 /// let result = f64::NAN.partial_cmp(&1.0);
1402 /// assert_eq!(result, None);
1403 /// ```
1404 #[must_use]
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 #[rustc_diagnostic_item = "cmp_partialord_cmp"]
1407 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1408
1409 /// Tests less than (for `self` and `other`) and is used by the `<` operator.
1410 ///
1411 /// # Examples
1412 ///
1413 /// ```
1414 /// assert_eq!(1.0 < 1.0, false);
1415 /// assert_eq!(1.0 < 2.0, true);
1416 /// assert_eq!(2.0 < 1.0, false);
1417 /// ```
1418 #[inline]
1419 #[must_use]
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 #[rustc_diagnostic_item = "cmp_partialord_lt"]
1422 fn lt(&self, other: &Rhs) -> bool {
1423 self.partial_cmp(other).is_some_and(Ordering::is_lt)
1424 }
1425
1426 /// Tests less than or equal to (for `self` and `other`) and is used by the
1427 /// `<=` operator.
1428 ///
1429 /// # Examples
1430 ///
1431 /// ```
1432 /// assert_eq!(1.0 <= 1.0, true);
1433 /// assert_eq!(1.0 <= 2.0, true);
1434 /// assert_eq!(2.0 <= 1.0, false);
1435 /// ```
1436 #[inline]
1437 #[must_use]
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 #[rustc_diagnostic_item = "cmp_partialord_le"]
1440 fn le(&self, other: &Rhs) -> bool {
1441 self.partial_cmp(other).is_some_and(Ordering::is_le)
1442 }
1443
1444 /// Tests greater than (for `self` and `other`) and is used by the `>`
1445 /// operator.
1446 ///
1447 /// # Examples
1448 ///
1449 /// ```
1450 /// assert_eq!(1.0 > 1.0, false);
1451 /// assert_eq!(1.0 > 2.0, false);
1452 /// assert_eq!(2.0 > 1.0, true);
1453 /// ```
1454 #[inline]
1455 #[must_use]
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 #[rustc_diagnostic_item = "cmp_partialord_gt"]
1458 fn gt(&self, other: &Rhs) -> bool {
1459 self.partial_cmp(other).is_some_and(Ordering::is_gt)
1460 }
1461
1462 /// Tests greater than or equal to (for `self` and `other`) and is used by
1463 /// the `>=` operator.
1464 ///
1465 /// # Examples
1466 ///
1467 /// ```
1468 /// assert_eq!(1.0 >= 1.0, true);
1469 /// assert_eq!(1.0 >= 2.0, false);
1470 /// assert_eq!(2.0 >= 1.0, true);
1471 /// ```
1472 #[inline]
1473 #[must_use]
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 #[rustc_diagnostic_item = "cmp_partialord_ge"]
1476 fn ge(&self, other: &Rhs) -> bool {
1477 self.partial_cmp(other).is_some_and(Ordering::is_ge)
1478 }
1479
1480 /// If `self == other`, returns `ControlFlow::Continue(())`.
1481 /// Otherwise, returns `ControlFlow::Break(self < other)`.
1482 ///
1483 /// This is useful for chaining together calls when implementing a lexical
1484 /// `PartialOrd::lt`, as it allows types (like primitives) which can cheaply
1485 /// check `==` and `<` separately to do rather than needing to calculate
1486 /// (then optimize out) the three-way `Ordering` result.
1487 #[inline]
1488 // Added to improve the behaviour of tuples; not necessarily stabilization-track.
1489 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1490 #[doc(hidden)]
1491 fn __chaining_lt(&self, other: &Rhs) -> ControlFlow<bool> {
1492 default_chaining_impl(self, other, Ordering::is_lt)
1493 }
1494
1495 /// Same as `__chaining_lt`, but for `<=` instead of `<`.
1496 #[inline]
1497 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1498 #[doc(hidden)]
1499 fn __chaining_le(&self, other: &Rhs) -> ControlFlow<bool> {
1500 default_chaining_impl(self, other, Ordering::is_le)
1501 }
1502
1503 /// Same as `__chaining_lt`, but for `>` instead of `<`.
1504 #[inline]
1505 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1506 #[doc(hidden)]
1507 fn __chaining_gt(&self, other: &Rhs) -> ControlFlow<bool> {
1508 default_chaining_impl(self, other, Ordering::is_gt)
1509 }
1510
1511 /// Same as `__chaining_lt`, but for `>=` instead of `<`.
1512 #[inline]
1513 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1514 #[doc(hidden)]
1515 fn __chaining_ge(&self, other: &Rhs) -> ControlFlow<bool> {
1516 default_chaining_impl(self, other, Ordering::is_ge)
1517 }
1518}
1519
1520#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1521const fn default_chaining_impl<T, U>(
1522 lhs: &T,
1523 rhs: &U,
1524 p: impl [const] FnOnce(Ordering) -> bool + [const] Destruct,
1525) -> ControlFlow<bool>
1526where
1527 T: [const] PartialOrd<U> + PointeeSized,
1528 U: PointeeSized,
1529{
1530 // It's important that this only call `partial_cmp` once, not call `eq` then
1531 // one of the relational operators. We don't want to `bcmp`-then-`memcp` a
1532 // `String`, for example, or similarly for other data structures (#108157).
1533 match <T as PartialOrd<U>>::partial_cmp(lhs, rhs) {
1534 Some(Equal) => ControlFlow::Continue(()),
1535 Some(c) => ControlFlow::Break(p(c)),
1536 None => ControlFlow::Break(false),
1537 }
1538}
1539
1540/// Derive macro generating an impl of the trait [`PartialOrd`].
1541/// The behavior of this macro is described in detail [here](PartialOrd#derivable).
1542#[rustc_builtin_macro]
1543#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1544#[allow_internal_unstable(core_intrinsics)]
1545pub macro PartialOrd($item:item) {
1546 /* compiler built-in */
1547}
1548
1549/// Compares and returns the minimum of two values.
1550///
1551/// Returns the first argument if the comparison determines them to be equal.
1552///
1553/// Internally uses an alias to [`Ord::min`].
1554///
1555/// # Examples
1556///
1557/// ```
1558/// use std::cmp;
1559///
1560/// assert_eq!(cmp::min(1, 2), 1);
1561/// assert_eq!(cmp::min(2, 2), 2);
1562/// ```
1563/// ```
1564/// use std::cmp::{self, Ordering};
1565///
1566/// #[derive(Eq)]
1567/// struct Equal(&'static str);
1568///
1569/// impl PartialEq for Equal {
1570/// fn eq(&self, other: &Self) -> bool { true }
1571/// }
1572/// impl PartialOrd for Equal {
1573/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1574/// }
1575/// impl Ord for Equal {
1576/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1577/// }
1578///
1579/// assert_eq!(cmp::min(Equal("v1"), Equal("v2")).0, "v1");
1580/// ```
1581#[inline]
1582#[must_use]
1583#[stable(feature = "rust1", since = "1.0.0")]
1584#[rustc_diagnostic_item = "cmp_min"]
1585#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1586pub const fn min<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1587 v1.min(v2)
1588}
1589
1590/// Returns the minimum of two values with respect to the specified comparison function.
1591///
1592/// Returns the first argument if the comparison determines them to be equal.
1593///
1594/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1595/// always passed as the first argument and `v2` as the second.
1596///
1597/// # Examples
1598///
1599/// ```
1600/// use std::cmp;
1601///
1602/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1603///
1604/// let result = cmp::min_by(2, -1, abs_cmp);
1605/// assert_eq!(result, -1);
1606///
1607/// let result = cmp::min_by(2, -3, abs_cmp);
1608/// assert_eq!(result, 2);
1609///
1610/// let result = cmp::min_by(1, -1, abs_cmp);
1611/// assert_eq!(result, 1);
1612/// ```
1613#[inline]
1614#[must_use]
1615#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1616#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1617pub const fn min_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1618 v1: T,
1619 v2: T,
1620 compare: F,
1621) -> T {
1622 if compare(&v1, &v2).is_le() { v1 } else { v2 }
1623}
1624
1625/// Returns the element that gives the minimum value from the specified function.
1626///
1627/// Returns the first argument if the comparison determines them to be equal.
1628///
1629/// # Examples
1630///
1631/// ```
1632/// use std::cmp;
1633///
1634/// let result = cmp::min_by_key(2, -1, |x: &i32| x.abs());
1635/// assert_eq!(result, -1);
1636///
1637/// let result = cmp::min_by_key(2, -3, |x: &i32| x.abs());
1638/// assert_eq!(result, 2);
1639///
1640/// let result = cmp::min_by_key(1, -1, |x: &i32| x.abs());
1641/// assert_eq!(result, 1);
1642/// ```
1643#[inline]
1644#[must_use]
1645#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1646#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1647pub const fn min_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1648where
1649 T: [const] Destruct,
1650 F: [const] FnMut(&T) -> K + [const] Destruct,
1651 K: [const] Ord + [const] Destruct,
1652{
1653 if f(&v2) < f(&v1) { v2 } else { v1 }
1654}
1655
1656/// Compares and returns the maximum of two values.
1657///
1658/// Returns the second argument if the comparison determines them to be equal.
1659///
1660/// Internally uses an alias to [`Ord::max`].
1661///
1662/// # Examples
1663///
1664/// ```
1665/// use std::cmp;
1666///
1667/// assert_eq!(cmp::max(1, 2), 2);
1668/// assert_eq!(cmp::max(2, 2), 2);
1669/// ```
1670/// ```
1671/// use std::cmp::{self, Ordering};
1672///
1673/// #[derive(Eq)]
1674/// struct Equal(&'static str);
1675///
1676/// impl PartialEq for Equal {
1677/// fn eq(&self, other: &Self) -> bool { true }
1678/// }
1679/// impl PartialOrd for Equal {
1680/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1681/// }
1682/// impl Ord for Equal {
1683/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1684/// }
1685///
1686/// assert_eq!(cmp::max(Equal("v1"), Equal("v2")).0, "v2");
1687/// ```
1688#[inline]
1689#[must_use]
1690#[stable(feature = "rust1", since = "1.0.0")]
1691#[rustc_diagnostic_item = "cmp_max"]
1692#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1693pub const fn max<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1694 v1.max(v2)
1695}
1696
1697/// Returns the maximum of two values with respect to the specified comparison function.
1698///
1699/// Returns the second argument if the comparison determines them to be equal.
1700///
1701/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1702/// always passed as the first argument and `v2` as the second.
1703///
1704/// # Examples
1705///
1706/// ```
1707/// use std::cmp;
1708///
1709/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1710///
1711/// let result = cmp::max_by(3, -2, abs_cmp) ;
1712/// assert_eq!(result, 3);
1713///
1714/// let result = cmp::max_by(1, -2, abs_cmp);
1715/// assert_eq!(result, -2);
1716///
1717/// let result = cmp::max_by(1, -1, abs_cmp);
1718/// assert_eq!(result, -1);
1719/// ```
1720#[inline]
1721#[must_use]
1722#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1723#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1724pub const fn max_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1725 v1: T,
1726 v2: T,
1727 compare: F,
1728) -> T {
1729 if compare(&v1, &v2).is_gt() { v1 } else { v2 }
1730}
1731
1732/// Returns the element that gives the maximum value from the specified function.
1733///
1734/// Returns the second argument if the comparison determines them to be equal.
1735///
1736/// # Examples
1737///
1738/// ```
1739/// use std::cmp;
1740///
1741/// let result = cmp::max_by_key(3, -2, |x: &i32| x.abs());
1742/// assert_eq!(result, 3);
1743///
1744/// let result = cmp::max_by_key(1, -2, |x: &i32| x.abs());
1745/// assert_eq!(result, -2);
1746///
1747/// let result = cmp::max_by_key(1, -1, |x: &i32| x.abs());
1748/// assert_eq!(result, -1);
1749/// ```
1750#[inline]
1751#[must_use]
1752#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1753#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1754pub const fn max_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1755where
1756 T: [const] Destruct,
1757 F: [const] FnMut(&T) -> K + [const] Destruct,
1758 K: [const] Ord + [const] Destruct,
1759{
1760 if f(&v2) < f(&v1) { v1 } else { v2 }
1761}
1762
1763/// Compares and sorts two values, returning minimum and maximum.
1764///
1765/// Returns `[v1, v2]` if the comparison determines them to be equal.
1766///
1767/// # Examples
1768///
1769/// ```
1770/// #![feature(cmp_minmax)]
1771/// use std::cmp;
1772///
1773/// assert_eq!(cmp::minmax(1, 2), [1, 2]);
1774/// assert_eq!(cmp::minmax(2, 1), [1, 2]);
1775///
1776/// // You can destructure the result using array patterns
1777/// let [min, max] = cmp::minmax(42, 17);
1778/// assert_eq!(min, 17);
1779/// assert_eq!(max, 42);
1780/// ```
1781/// ```
1782/// #![feature(cmp_minmax)]
1783/// use std::cmp::{self, Ordering};
1784///
1785/// #[derive(Eq)]
1786/// struct Equal(&'static str);
1787///
1788/// impl PartialEq for Equal {
1789/// fn eq(&self, other: &Self) -> bool { true }
1790/// }
1791/// impl PartialOrd for Equal {
1792/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1793/// }
1794/// impl Ord for Equal {
1795/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1796/// }
1797///
1798/// assert_eq!(cmp::minmax(Equal("v1"), Equal("v2")).map(|v| v.0), ["v1", "v2"]);
1799/// ```
1800#[inline]
1801#[must_use]
1802#[unstable(feature = "cmp_minmax", issue = "115939")]
1803#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1804pub const fn minmax<T>(v1: T, v2: T) -> [T; 2]
1805where
1806 T: [const] Ord,
1807{
1808 if v2 < v1 { [v2, v1] } else { [v1, v2] }
1809}
1810
1811/// Returns minimum and maximum values with respect to the specified comparison function.
1812///
1813/// Returns `[v1, v2]` if the comparison determines them to be equal.
1814///
1815/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1816/// always passed as the first argument and `v2` as the second.
1817///
1818/// # Examples
1819///
1820/// ```
1821/// #![feature(cmp_minmax)]
1822/// use std::cmp;
1823///
1824/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1825///
1826/// assert_eq!(cmp::minmax_by(-2, 1, abs_cmp), [1, -2]);
1827/// assert_eq!(cmp::minmax_by(-1, 2, abs_cmp), [-1, 2]);
1828/// assert_eq!(cmp::minmax_by(-2, 2, abs_cmp), [-2, 2]);
1829///
1830/// // You can destructure the result using array patterns
1831/// let [min, max] = cmp::minmax_by(-42, 17, abs_cmp);
1832/// assert_eq!(min, 17);
1833/// assert_eq!(max, -42);
1834/// ```
1835#[inline]
1836#[must_use]
1837#[unstable(feature = "cmp_minmax", issue = "115939")]
1838#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1839pub const fn minmax_by<T, F>(v1: T, v2: T, compare: F) -> [T; 2]
1840where
1841 F: [const] FnOnce(&T, &T) -> Ordering,
1842{
1843 if compare(&v1, &v2).is_le() { [v1, v2] } else { [v2, v1] }
1844}
1845
1846/// Returns minimum and maximum values with respect to the specified key function.
1847///
1848/// Returns `[v1, v2]` if the comparison determines them to be equal.
1849///
1850/// # Examples
1851///
1852/// ```
1853/// #![feature(cmp_minmax)]
1854/// use std::cmp;
1855///
1856/// assert_eq!(cmp::minmax_by_key(-2, 1, |x: &i32| x.abs()), [1, -2]);
1857/// assert_eq!(cmp::minmax_by_key(-2, 2, |x: &i32| x.abs()), [-2, 2]);
1858///
1859/// // You can destructure the result using array patterns
1860/// let [min, max] = cmp::minmax_by_key(-42, 17, |x: &i32| x.abs());
1861/// assert_eq!(min, 17);
1862/// assert_eq!(max, -42);
1863/// ```
1864#[inline]
1865#[must_use]
1866#[unstable(feature = "cmp_minmax", issue = "115939")]
1867#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1868pub const fn minmax_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> [T; 2]
1869where
1870 F: [const] FnMut(&T) -> K + [const] Destruct,
1871 K: [const] Ord + [const] Destruct,
1872{
1873 if f(&v2) < f(&v1) { [v2, v1] } else { [v1, v2] }
1874}
1875
1876// Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1877mod impls {
1878 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1879 use crate::hint::unreachable_unchecked;
1880 use crate::marker::PointeeSized;
1881 use crate::ops::ControlFlow::{self, Break, Continue};
1882 use crate::panic::const_assert;
1883
1884 /// Implements `PartialEq` for primitive types.
1885 ///
1886 /// Primitive types have a compiler-defined primitive implementation of `==` and `!=`.
1887 /// This implements the `PartialEq` trait in terms of those primitive implementations.
1888 ///
1889 /// NOTE: Calling this on a non-primitive type (such as `()`)
1890 /// leads to an infinitely-looping self-recursive implementation.
1891 macro_rules! impl_partial_eq_for_primitive {
1892 ($($t:ty)*) => ($(
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1895 const impl PartialEq for $t {
1896 #[inline]
1897 fn eq(&self, other: &Self) -> bool { *self == *other }
1898 // Override the default to use the primitive implementation for `!=`.
1899 #[inline]
1900 fn ne(&self, other: &Self) -> bool { *self != *other }
1901 }
1902 )*)
1903 }
1904
1905 impl_partial_eq_for_primitive! {
1906 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128
1907 }
1908
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1911 const impl PartialEq for () {
1912 #[inline]
1913 fn eq(&self, _other: &()) -> bool {
1914 true
1915 }
1916 #[inline]
1917 fn ne(&self, _other: &()) -> bool {
1918 false
1919 }
1920 }
1921
1922 macro_rules! eq_impl {
1923 ($($t:ty)*) => ($(
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1926 const impl Eq for $t {}
1927 )*)
1928 }
1929
1930 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1931
1932 #[rustfmt::skip]
1933 macro_rules! partial_ord_methods_primitive_impl {
1934 () => {
1935 #[inline(always)]
1936 fn lt(&self, other: &Self) -> bool { *self < *other }
1937 #[inline(always)]
1938 fn le(&self, other: &Self) -> bool { *self <= *other }
1939 #[inline(always)]
1940 fn gt(&self, other: &Self) -> bool { *self > *other }
1941 #[inline(always)]
1942 fn ge(&self, other: &Self) -> bool { *self >= *other }
1943
1944 // These implementations are the same for `Ord` or `PartialOrd` types
1945 // because if either is NAN the `==` test will fail so we end up in
1946 // the `Break` case and the comparison will correctly return `false`.
1947
1948 #[inline]
1949 fn __chaining_lt(&self, other: &Self) -> ControlFlow<bool> {
1950 let (lhs, rhs) = (*self, *other);
1951 if lhs == rhs { Continue(()) } else { Break(lhs < rhs) }
1952 }
1953 #[inline]
1954 fn __chaining_le(&self, other: &Self) -> ControlFlow<bool> {
1955 let (lhs, rhs) = (*self, *other);
1956 if lhs == rhs { Continue(()) } else { Break(lhs <= rhs) }
1957 }
1958 #[inline]
1959 fn __chaining_gt(&self, other: &Self) -> ControlFlow<bool> {
1960 let (lhs, rhs) = (*self, *other);
1961 if lhs == rhs { Continue(()) } else { Break(lhs > rhs) }
1962 }
1963 #[inline]
1964 fn __chaining_ge(&self, other: &Self) -> ControlFlow<bool> {
1965 let (lhs, rhs) = (*self, *other);
1966 if lhs == rhs { Continue(()) } else { Break(lhs >= rhs) }
1967 }
1968 };
1969 }
1970
1971 macro_rules! partial_ord_impl {
1972 ($($t:ty)*) => ($(
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1975 const impl PartialOrd for $t {
1976 #[inline]
1977 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1978 match (*self <= *other, *self >= *other) {
1979 (false, false) => None,
1980 (false, true) => Some(Greater),
1981 (true, false) => Some(Less),
1982 (true, true) => Some(Equal),
1983 }
1984 }
1985
1986 partial_ord_methods_primitive_impl!();
1987 }
1988 )*)
1989 }
1990
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1993 const impl PartialOrd for () {
1994 #[inline]
1995 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1996 Some(Equal)
1997 }
1998 }
1999
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2002 const impl PartialOrd for bool {
2003 #[inline]
2004 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
2005 Some(self.cmp(other))
2006 }
2007
2008 partial_ord_methods_primitive_impl!();
2009 }
2010
2011 partial_ord_impl! { f16 f32 f64 f128 }
2012
2013 macro_rules! ord_impl {
2014 ($($t:ty)*) => ($(
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2017 const impl PartialOrd for $t {
2018 #[inline]
2019 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2020 Some(crate::intrinsics::three_way_compare(*self, *other))
2021 }
2022
2023 partial_ord_methods_primitive_impl!();
2024 }
2025
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2028 const impl Ord for $t {
2029 #[inline]
2030 fn cmp(&self, other: &Self) -> Ordering {
2031 crate::intrinsics::three_way_compare(*self, *other)
2032 }
2033
2034 #[inline]
2035 #[track_caller]
2036 fn clamp(self, min: Self, max: Self) -> Self
2037 {
2038 const_assert!(
2039 min <= max,
2040 "min > max",
2041 "min > max. min = {min:?}, max = {max:?}",
2042 min: $t,
2043 max: $t,
2044 );
2045 if self < min {
2046 min
2047 } else if self > max {
2048 max
2049 } else {
2050 self
2051 }
2052 }
2053 }
2054 )*)
2055 }
2056
2057 #[stable(feature = "rust1", since = "1.0.0")]
2058 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2059 const impl Ord for () {
2060 #[inline]
2061 fn cmp(&self, _other: &()) -> Ordering {
2062 Equal
2063 }
2064 }
2065
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2068 const impl Ord for bool {
2069 #[inline]
2070 fn cmp(&self, other: &bool) -> Ordering {
2071 // Casting to i8's and converting the difference to an Ordering generates
2072 // more optimal assembly.
2073 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
2074 match (*self as i8) - (*other as i8) {
2075 -1 => Less,
2076 0 => Equal,
2077 1 => Greater,
2078 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
2079 _ => unsafe { unreachable_unchecked() },
2080 }
2081 }
2082
2083 #[inline]
2084 fn min(self, other: bool) -> bool {
2085 self & other
2086 }
2087
2088 #[inline]
2089 fn max(self, other: bool) -> bool {
2090 self | other
2091 }
2092
2093 #[inline]
2094 fn clamp(self, min: bool, max: bool) -> bool {
2095 assert!(min <= max);
2096 self.max(min).min(max)
2097 }
2098 }
2099
2100 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
2101
2102 #[unstable(feature = "never_type", issue = "35121")]
2103 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2104 const impl PartialEq for ! {
2105 #[inline]
2106 fn eq(&self, _: &!) -> bool {
2107 *self
2108 }
2109 }
2110
2111 #[unstable(feature = "never_type", issue = "35121")]
2112 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2113 const impl Eq for ! {}
2114
2115 #[unstable(feature = "never_type", issue = "35121")]
2116 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2117 const impl PartialOrd for ! {
2118 #[inline]
2119 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
2120 *self
2121 }
2122 }
2123
2124 #[unstable(feature = "never_type", issue = "35121")]
2125 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2126 const impl Ord for ! {
2127 #[inline]
2128 fn cmp(&self, _: &!) -> Ordering {
2129 *self
2130 }
2131 }
2132
2133 // & pointers
2134
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2137 const impl<A: PointeeSized, B: PointeeSized> PartialEq<&B> for &A
2138 where
2139 A: [const] PartialEq<B>,
2140 {
2141 #[inline]
2142 fn eq(&self, other: &&B) -> bool {
2143 PartialEq::eq(*self, *other)
2144 }
2145 #[inline]
2146 fn ne(&self, other: &&B) -> bool {
2147 PartialEq::ne(*self, *other)
2148 }
2149 }
2150 #[stable(feature = "rust1", since = "1.0.0")]
2151 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2152 const impl<A: PointeeSized, B: PointeeSized> PartialOrd<&B> for &A
2153 where
2154 A: [const] PartialOrd<B>,
2155 {
2156 #[inline]
2157 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
2158 PartialOrd::partial_cmp(*self, *other)
2159 }
2160 #[inline]
2161 fn lt(&self, other: &&B) -> bool {
2162 PartialOrd::lt(*self, *other)
2163 }
2164 #[inline]
2165 fn le(&self, other: &&B) -> bool {
2166 PartialOrd::le(*self, *other)
2167 }
2168 #[inline]
2169 fn gt(&self, other: &&B) -> bool {
2170 PartialOrd::gt(*self, *other)
2171 }
2172 #[inline]
2173 fn ge(&self, other: &&B) -> bool {
2174 PartialOrd::ge(*self, *other)
2175 }
2176 #[inline]
2177 fn __chaining_lt(&self, other: &&B) -> ControlFlow<bool> {
2178 PartialOrd::__chaining_lt(*self, *other)
2179 }
2180 #[inline]
2181 fn __chaining_le(&self, other: &&B) -> ControlFlow<bool> {
2182 PartialOrd::__chaining_le(*self, *other)
2183 }
2184 #[inline]
2185 fn __chaining_gt(&self, other: &&B) -> ControlFlow<bool> {
2186 PartialOrd::__chaining_gt(*self, *other)
2187 }
2188 #[inline]
2189 fn __chaining_ge(&self, other: &&B) -> ControlFlow<bool> {
2190 PartialOrd::__chaining_ge(*self, *other)
2191 }
2192 }
2193 #[stable(feature = "rust1", since = "1.0.0")]
2194 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2195 const impl<A: PointeeSized> Ord for &A
2196 where
2197 A: [const] Ord,
2198 {
2199 #[inline]
2200 fn cmp(&self, other: &Self) -> Ordering {
2201 Ord::cmp(*self, *other)
2202 }
2203 }
2204 #[stable(feature = "rust1", since = "1.0.0")]
2205 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2206 const impl<A: PointeeSized> Eq for &A where A: [const] Eq {}
2207
2208 // &mut pointers
2209
2210 #[stable(feature = "rust1", since = "1.0.0")]
2211 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2212 const impl<A: PointeeSized, B: PointeeSized> PartialEq<&mut B> for &mut A
2213 where
2214 A: [const] PartialEq<B>,
2215 {
2216 #[inline]
2217 fn eq(&self, other: &&mut B) -> bool {
2218 PartialEq::eq(*self, *other)
2219 }
2220 #[inline]
2221 fn ne(&self, other: &&mut B) -> bool {
2222 PartialEq::ne(*self, *other)
2223 }
2224 }
2225 #[stable(feature = "rust1", since = "1.0.0")]
2226 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2227 const impl<A: PointeeSized, B: PointeeSized> PartialOrd<&mut B> for &mut A
2228 where
2229 A: [const] PartialOrd<B>,
2230 {
2231 #[inline]
2232 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
2233 PartialOrd::partial_cmp(*self, *other)
2234 }
2235 #[inline]
2236 fn lt(&self, other: &&mut B) -> bool {
2237 PartialOrd::lt(*self, *other)
2238 }
2239 #[inline]
2240 fn le(&self, other: &&mut B) -> bool {
2241 PartialOrd::le(*self, *other)
2242 }
2243 #[inline]
2244 fn gt(&self, other: &&mut B) -> bool {
2245 PartialOrd::gt(*self, *other)
2246 }
2247 #[inline]
2248 fn ge(&self, other: &&mut B) -> bool {
2249 PartialOrd::ge(*self, *other)
2250 }
2251 #[inline]
2252 fn __chaining_lt(&self, other: &&mut B) -> ControlFlow<bool> {
2253 PartialOrd::__chaining_lt(*self, *other)
2254 }
2255 #[inline]
2256 fn __chaining_le(&self, other: &&mut B) -> ControlFlow<bool> {
2257 PartialOrd::__chaining_le(*self, *other)
2258 }
2259 #[inline]
2260 fn __chaining_gt(&self, other: &&mut B) -> ControlFlow<bool> {
2261 PartialOrd::__chaining_gt(*self, *other)
2262 }
2263 #[inline]
2264 fn __chaining_ge(&self, other: &&mut B) -> ControlFlow<bool> {
2265 PartialOrd::__chaining_ge(*self, *other)
2266 }
2267 }
2268 #[stable(feature = "rust1", since = "1.0.0")]
2269 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2270 const impl<A: PointeeSized> Ord for &mut A
2271 where
2272 A: [const] Ord,
2273 {
2274 #[inline]
2275 fn cmp(&self, other: &Self) -> Ordering {
2276 Ord::cmp(*self, *other)
2277 }
2278 }
2279 #[stable(feature = "rust1", since = "1.0.0")]
2280 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2281 const impl<A: PointeeSized> Eq for &mut A where A: [const] Eq {}
2282
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2285 const impl<A: PointeeSized, B: PointeeSized> PartialEq<&mut B> for &A
2286 where
2287 A: [const] PartialEq<B>,
2288 {
2289 #[inline]
2290 fn eq(&self, other: &&mut B) -> bool {
2291 PartialEq::eq(*self, *other)
2292 }
2293 #[inline]
2294 fn ne(&self, other: &&mut B) -> bool {
2295 PartialEq::ne(*self, *other)
2296 }
2297 }
2298
2299 #[stable(feature = "rust1", since = "1.0.0")]
2300 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2301 const impl<A: PointeeSized, B: PointeeSized> PartialEq<&B> for &mut A
2302 where
2303 A: [const] PartialEq<B>,
2304 {
2305 #[inline]
2306 fn eq(&self, other: &&B) -> bool {
2307 PartialEq::eq(*self, *other)
2308 }
2309 #[inline]
2310 fn ne(&self, other: &&B) -> bool {
2311 PartialEq::ne(*self, *other)
2312 }
2313 }
2314}