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