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