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