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