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