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
28#[cfg(not(feature = "ferrocene_certified"))]
29mod bytewise;
30#[cfg(not(feature = "ferrocene_certified"))]
31pub(crate) use bytewise::BytewiseEq;
32
33use self::Ordering::*;
34use crate::marker::{Destruct, PointeeSized};
35use crate::ops::ControlFlow;
36
37/// Trait for comparisons using the equality operator.
38///
39/// Implementing this trait for types provides the `==` and `!=` operators for
40/// those types.
41///
42/// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
43/// We use the easier-to-read infix notation in the remainder of this documentation.
44///
45/// This trait allows for comparisons using the equality operator, for types
46/// that do not have a full equivalence relation. For example, in floating point
47/// numbers `NaN != NaN`, so floating point types implement `PartialEq` but not
48/// [`trait@Eq`]. Formally speaking, when `Rhs == Self`, this trait corresponds
49/// to a [partial equivalence relation].
50///
51/// [partial equivalence relation]: https://en.wikipedia.org/wiki/Partial_equivalence_relation
52///
53/// Implementations must ensure that `eq` and `ne` are consistent with each other:
54///
55/// - `a != b` if and only if `!(a == b)`.
56///
57/// The default implementation of `ne` provides this consistency and is almost
58/// always sufficient. It should not be overridden without very good reason.
59///
60/// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
61/// be consistent with `PartialEq` (see the documentation of those traits for the exact
62/// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
63/// manually implementing others.
64///
65/// The equality relation `==` must satisfy the following conditions
66/// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
67///
68/// - **Symmetry**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
69/// implies `b == a`**; and
70///
71/// - **Transitivity**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
72/// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
73/// This must also work for longer chains, such as when `A: PartialEq<B>`, `B: PartialEq<C>`,
74/// `C: PartialEq<D>`, and `A: PartialEq<D>` all exist.
75///
76/// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
77/// (transitive) impls are not forced to exist, but these requirements apply
78/// whenever they do exist.
79///
80/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
81/// specified, but users of the trait must ensure that such logic errors do *not* result in
82/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
83/// methods.
84///
85/// ## Cross-crate considerations
86///
87/// Upholding the requirements stated above can become tricky when one crate implements `PartialEq`
88/// for a type of another crate (i.e., to allow comparing one of its own types with a type from the
89/// standard library). The recommendation is to never implement this trait for a foreign type. In
90/// other words, such a crate should do `impl PartialEq<ForeignType> for LocalType`, but it should
91/// *not* do `impl PartialEq<LocalType> for ForeignType`.
92///
93/// This avoids the problem of transitive chains that criss-cross crate boundaries: for all local
94/// types `T`, you may assume that no other crate will add `impl`s that allow comparing `T == U`. In
95/// other words, if other crates add `impl`s that allow building longer transitive chains `U1 == ...
96/// == T == V1 == ...`, then all the types that appear to the right of `T` must be types that the
97/// crate defining `T` already knows about. This rules out transitive chains where downstream crates
98/// can add new `impl`s that "stitch together" comparisons of foreign types in ways that violate
99/// transitivity.
100///
101/// Not having such foreign `impl`s also avoids forward compatibility issues where one crate adding
102/// more `PartialEq` implementations can cause build failures in downstream crates.
103///
104/// ## Derivable
105///
106/// This trait can be used with `#[derive]`. When `derive`d on structs, two
107/// instances are equal if all fields are equal, and not equal if any fields
108/// are not equal. When `derive`d on enums, two instances are equal if they
109/// are the same variant and all fields are equal.
110///
111/// ## How can I implement `PartialEq`?
112///
113/// An example implementation for a domain in which two books are considered
114/// the same book if their ISBN matches, even if the formats differ:
115///
116/// ```
117/// enum BookFormat {
118/// Paperback,
119/// Hardback,
120/// Ebook,
121/// }
122///
123/// struct Book {
124/// isbn: i32,
125/// format: BookFormat,
126/// }
127///
128/// impl PartialEq for Book {
129/// fn eq(&self, other: &Self) -> bool {
130/// self.isbn == other.isbn
131/// }
132/// }
133///
134/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
135/// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
136/// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
137///
138/// assert!(b1 == b2);
139/// assert!(b1 != b3);
140/// ```
141///
142/// ## How can I compare two different types?
143///
144/// The type you can compare with is controlled by `PartialEq`'s type parameter.
145/// For example, let's tweak our previous code a bit:
146///
147/// ```
148/// // The derive implements <BookFormat> == <BookFormat> comparisons
149/// #[derive(PartialEq)]
150/// enum BookFormat {
151/// Paperback,
152/// Hardback,
153/// Ebook,
154/// }
155///
156/// struct Book {
157/// isbn: i32,
158/// format: BookFormat,
159/// }
160///
161/// // Implement <Book> == <BookFormat> comparisons
162/// impl PartialEq<BookFormat> for Book {
163/// fn eq(&self, other: &BookFormat) -> bool {
164/// self.format == *other
165/// }
166/// }
167///
168/// // Implement <BookFormat> == <Book> comparisons
169/// impl PartialEq<Book> for BookFormat {
170/// fn eq(&self, other: &Book) -> bool {
171/// *self == other.format
172/// }
173/// }
174///
175/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
176///
177/// assert!(b1 == BookFormat::Paperback);
178/// assert!(BookFormat::Ebook != b1);
179/// ```
180///
181/// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
182/// we allow `BookFormat`s to be compared with `Book`s.
183///
184/// A comparison like the one above, which ignores some fields of the struct,
185/// can be dangerous. It can easily lead to an unintended violation of the
186/// requirements for a partial equivalence relation. For example, if we kept
187/// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
188/// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
189/// via the manual implementation from the first example) then the result would
190/// violate transitivity:
191///
192/// ```should_panic
193/// #[derive(PartialEq)]
194/// enum BookFormat {
195/// Paperback,
196/// Hardback,
197/// Ebook,
198/// }
199///
200/// #[derive(PartialEq)]
201/// struct Book {
202/// isbn: i32,
203/// format: BookFormat,
204/// }
205///
206/// impl PartialEq<BookFormat> for Book {
207/// fn eq(&self, other: &BookFormat) -> bool {
208/// self.format == *other
209/// }
210/// }
211///
212/// impl PartialEq<Book> for BookFormat {
213/// fn eq(&self, other: &Book) -> bool {
214/// *self == other.format
215/// }
216/// }
217///
218/// fn main() {
219/// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
220/// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
221///
222/// assert!(b1 == BookFormat::Paperback);
223/// assert!(BookFormat::Paperback == b2);
224///
225/// // The following should hold by transitivity but doesn't.
226/// assert!(b1 == b2); // <-- PANICS
227/// }
228/// ```
229///
230/// # Examples
231///
232/// ```
233/// let x: u32 = 0;
234/// let y: u32 = 1;
235///
236/// assert_eq!(x == y, false);
237/// assert_eq!(x.eq(&y), false);
238/// ```
239///
240/// [`eq`]: PartialEq::eq
241/// [`ne`]: PartialEq::ne
242#[lang = "eq"]
243#[stable(feature = "rust1", since = "1.0.0")]
244#[doc(alias = "==")]
245#[doc(alias = "!=")]
246#[rustc_on_unimplemented(
247 message = "can't compare `{Self}` with `{Rhs}`",
248 label = "no implementation for `{Self} == {Rhs}`",
249 append_const_msg
250)]
251#[rustc_diagnostic_item = "PartialEq"]
252#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
253pub const trait PartialEq<Rhs: PointeeSized = Self>: PointeeSized {
254 /// Tests for `self` and `other` values to be equal, and is used by `==`.
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 /// Tests for `!=`. The default implementation is almost always sufficient,
261 /// and should not be overridden without very good reason.
262 #[inline]
263 #[must_use]
264 #[stable(feature = "rust1", since = "1.0.0")]
265 #[rustc_diagnostic_item = "cmp_partialeq_ne"]
266 fn ne(&self, other: &Rhs) -> bool {
267 !self.eq(other)
268 }
269}
270
271/// Derive macro generating an impl of the trait [`PartialEq`].
272/// The behavior of this macro is described in detail [here](PartialEq#derivable).
273#[rustc_builtin_macro]
274#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
275#[allow_internal_unstable(core_intrinsics, structural_match)]
276pub macro PartialEq($item:item) {
277 /* compiler built-in */
278}
279
280/// Trait for comparisons corresponding to [equivalence relations](
281/// https://en.wikipedia.org/wiki/Equivalence_relation).
282///
283/// The primary difference to [`PartialEq`] is the additional requirement for reflexivity. A type
284/// that implements [`PartialEq`] guarantees that for all `a`, `b` and `c`:
285///
286/// - symmetric: `a == b` implies `b == a` and `a != b` implies `!(a == b)`
287/// - transitive: `a == b` and `b == c` implies `a == c`
288///
289/// `Eq`, which builds on top of [`PartialEq`] also implies:
290///
291/// - reflexive: `a == a`
292///
293/// This property cannot be checked by the compiler, and therefore `Eq` is a trait without methods.
294///
295/// Violating this property is a logic error. The behavior resulting from a logic error is not
296/// specified, but users of the trait must ensure that such logic errors do *not* result in
297/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
298/// methods.
299///
300/// Floating point types such as [`f32`] and [`f64`] implement only [`PartialEq`] but *not* `Eq`
301/// because `NaN` != `NaN`.
302///
303/// ## Derivable
304///
305/// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has no extra methods, it
306/// is only informing the compiler that this is an equivalence relation rather than a partial
307/// equivalence relation. Note that the `derive` strategy requires all fields are `Eq`, which isn't
308/// always desired.
309///
310/// ## How can I implement `Eq`?
311///
312/// If you cannot use the `derive` strategy, specify that your type implements `Eq`, which has no
313/// extra methods:
314///
315/// ```
316/// enum BookFormat {
317/// Paperback,
318/// Hardback,
319/// Ebook,
320/// }
321///
322/// struct Book {
323/// isbn: i32,
324/// format: BookFormat,
325/// }
326///
327/// impl PartialEq for Book {
328/// fn eq(&self, other: &Self) -> bool {
329/// self.isbn == other.isbn
330/// }
331/// }
332///
333/// impl Eq for Book {}
334/// ```
335#[doc(alias = "==")]
336#[doc(alias = "!=")]
337#[stable(feature = "rust1", since = "1.0.0")]
338#[rustc_diagnostic_item = "Eq"]
339#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
340pub const trait Eq: [const] PartialEq<Self> + PointeeSized {
341 // this method is used solely by `impl Eq or #[derive(Eq)]` to assert that every component of a
342 // type implements `Eq` itself. The current deriving infrastructure means doing this assertion
343 // without using a method on this trait is nearly impossible.
344 //
345 // This should never be implemented by hand.
346 #[doc(hidden)]
347 #[coverage(off)]
348 #[inline]
349 #[stable(feature = "rust1", since = "1.0.0")]
350 fn assert_receiver_is_total_eq(&self) {}
351}
352
353/// Derive macro generating an impl of the trait [`Eq`].
354#[rustc_builtin_macro]
355#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
356#[allow_internal_unstable(core_intrinsics, derive_eq, structural_match)]
357#[allow_internal_unstable(coverage_attribute)]
358pub macro Eq($item:item) {
359 /* compiler built-in */
360}
361
362// FIXME: this struct is used solely by #[derive] to
363// assert that every component of a type implements Eq.
364//
365// This struct should never appear in user code.
366#[doc(hidden)]
367#[allow(missing_debug_implementations)]
368#[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
369#[cfg(not(feature = "ferrocene_certified"))]
370pub struct AssertParamIsEq<T: Eq + PointeeSized> {
371 _field: crate::marker::PhantomData<T>,
372}
373
374/// An `Ordering` is the result of a comparison between two values.
375///
376/// # Examples
377///
378/// ```
379/// use std::cmp::Ordering;
380///
381/// assert_eq!(1.cmp(&2), Ordering::Less);
382///
383/// assert_eq!(1.cmp(&1), Ordering::Equal);
384///
385/// assert_eq!(2.cmp(&1), Ordering::Greater);
386/// ```
387#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Debug, Hash))]
388#[rustfmt::skip] // Ferrocene addition: avoid multi-line cfg_attr
389#[cfg_attr(not(feature = "ferrocene_certified"), 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_certified"))]
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_certified"))]
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_certified"))]
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_certified"))]
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_certified"))]
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)]
1115#[cfg(not(feature = "ferrocene_certified"))]
1116pub macro Ord($item:item) {
1117 /* compiler built-in */
1118}
1119
1120/// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).
1121///
1122/// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using the `<`, `<=`, `>`, and
1123/// `>=` operators, respectively.
1124///
1125/// This trait should **only** contain the comparison logic for a type **if one plans on only
1126/// implementing `PartialOrd` but not [`Ord`]**. Otherwise the comparison logic should be in [`Ord`]
1127/// and this trait implemented with `Some(self.cmp(other))`.
1128///
1129/// The methods of this trait must be consistent with each other and with those of [`PartialEq`].
1130/// The following conditions must hold:
1131///
1132/// 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
1133/// 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
1134/// 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
1135/// 4. `a <= b` if and only if `a < b || a == b`
1136/// 5. `a >= b` if and only if `a > b || a == b`
1137/// 6. `a != b` if and only if `!(a == b)`.
1138///
1139/// Conditions 2–5 above are ensured by the default implementation. Condition 6 is already ensured
1140/// by [`PartialEq`].
1141///
1142/// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
1143/// `partial_cmp` (see the documentation of that trait for the exact requirements). It's easy to
1144/// accidentally make them disagree by deriving some of the traits and manually implementing others.
1145///
1146/// The comparison relations must satisfy the following conditions (for all `a`, `b`, `c` of type
1147/// `A`, `B`, `C`):
1148///
1149/// - **Transitivity**: if `A: PartialOrd<B>` and `B: PartialOrd<C>` and `A: PartialOrd<C>`, then `a
1150/// < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. This must also
1151/// work for longer chains, such as when `A: PartialOrd<B>`, `B: PartialOrd<C>`, `C:
1152/// PartialOrd<D>`, and `A: PartialOrd<D>` all exist.
1153/// - **Duality**: if `A: PartialOrd<B>` and `B: PartialOrd<A>`, then `a < b` if and only if `b >
1154/// a`.
1155///
1156/// Note that the `B: PartialOrd<A>` (dual) and `A: PartialOrd<C>` (transitive) impls are not forced
1157/// to exist, but these requirements apply whenever they do exist.
1158///
1159/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
1160/// specified, but users of the trait must ensure that such logic errors do *not* result in
1161/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
1162/// methods.
1163///
1164/// ## Cross-crate considerations
1165///
1166/// Upholding the requirements stated above can become tricky when one crate implements `PartialOrd`
1167/// for a type of another crate (i.e., to allow comparing one of its own types with a type from the
1168/// standard library). The recommendation is to never implement this trait for a foreign type. In
1169/// other words, such a crate should do `impl PartialOrd<ForeignType> for LocalType`, but it should
1170/// *not* do `impl PartialOrd<LocalType> for ForeignType`.
1171///
1172/// This avoids the problem of transitive chains that criss-cross crate boundaries: for all local
1173/// types `T`, you may assume that no other crate will add `impl`s that allow comparing `T < U`. In
1174/// other words, if other crates add `impl`s that allow building longer transitive chains `U1 < ...
1175/// < T < V1 < ...`, then all the types that appear to the right of `T` must be types that the crate
1176/// defining `T` already knows about. This rules out transitive chains where downstream crates can
1177/// add new `impl`s that "stitch together" comparisons of foreign types in ways that violate
1178/// transitivity.
1179///
1180/// Not having such foreign `impl`s also avoids forward compatibility issues where one crate adding
1181/// more `PartialOrd` implementations can cause build failures in downstream crates.
1182///
1183/// ## Corollaries
1184///
1185/// The following corollaries follow from the above requirements:
1186///
1187/// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
1188/// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
1189/// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
1190///
1191/// ## Strict and non-strict partial orders
1192///
1193/// The `<` and `>` operators behave according to a *strict* partial order. However, `<=` and `>=`
1194/// do **not** behave according to a *non-strict* partial order. That is because mathematically, a
1195/// non-strict partial order would require reflexivity, i.e. `a <= a` would need to be true for
1196/// every `a`. This isn't always the case for types that implement `PartialOrd`, for example:
1197///
1198/// ```
1199/// let a = f64::sqrt(-1.0);
1200/// assert_eq!(a <= a, false);
1201/// ```
1202///
1203/// ## Derivable
1204///
1205/// This trait can be used with `#[derive]`.
1206///
1207/// When `derive`d on structs, it will produce a
1208/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the
1209/// top-to-bottom declaration order of the struct's members.
1210///
1211/// When `derive`d on enums, variants are primarily ordered by their discriminants. Secondarily,
1212/// they are ordered by their fields. By default, the discriminant is smallest for variants at the
1213/// top, and largest for variants at the bottom. Here's an example:
1214///
1215/// ```
1216/// #[derive(PartialEq, PartialOrd)]
1217/// enum E {
1218/// Top,
1219/// Bottom,
1220/// }
1221///
1222/// assert!(E::Top < E::Bottom);
1223/// ```
1224///
1225/// However, manually setting the discriminants can override this default behavior:
1226///
1227/// ```
1228/// #[derive(PartialEq, PartialOrd)]
1229/// enum E {
1230/// Top = 2,
1231/// Bottom = 1,
1232/// }
1233///
1234/// assert!(E::Bottom < E::Top);
1235/// ```
1236///
1237/// ## How can I implement `PartialOrd`?
1238///
1239/// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
1240/// generated from default implementations.
1241///
1242/// However it remains possible to implement the others separately for types which do not have a
1243/// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 == false`
1244/// (cf. IEEE 754-2008 section 5.11).
1245///
1246/// `PartialOrd` requires your type to be [`PartialEq`].
1247///
1248/// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
1249///
1250/// ```
1251/// use std::cmp::Ordering;
1252///
1253/// struct Person {
1254/// id: u32,
1255/// name: String,
1256/// height: u32,
1257/// }
1258///
1259/// impl PartialOrd for Person {
1260/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1261/// Some(self.cmp(other))
1262/// }
1263/// }
1264///
1265/// impl Ord for Person {
1266/// fn cmp(&self, other: &Self) -> Ordering {
1267/// self.height.cmp(&other.height)
1268/// }
1269/// }
1270///
1271/// impl PartialEq for Person {
1272/// fn eq(&self, other: &Self) -> bool {
1273/// self.height == other.height
1274/// }
1275/// }
1276///
1277/// impl Eq for Person {}
1278/// ```
1279///
1280/// You may also find it useful to use [`partial_cmp`] on your type's fields. Here is an example of
1281/// `Person` types who have a floating-point `height` field that is the only field to be used for
1282/// sorting:
1283///
1284/// ```
1285/// use std::cmp::Ordering;
1286///
1287/// struct Person {
1288/// id: u32,
1289/// name: String,
1290/// height: f64,
1291/// }
1292///
1293/// impl PartialOrd for Person {
1294/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1295/// self.height.partial_cmp(&other.height)
1296/// }
1297/// }
1298///
1299/// impl PartialEq for Person {
1300/// fn eq(&self, other: &Self) -> bool {
1301/// self.height == other.height
1302/// }
1303/// }
1304/// ```
1305///
1306/// ## Examples of incorrect `PartialOrd` implementations
1307///
1308/// ```
1309/// use std::cmp::Ordering;
1310///
1311/// #[derive(PartialEq, Debug)]
1312/// struct Character {
1313/// health: u32,
1314/// experience: u32,
1315/// }
1316///
1317/// impl PartialOrd for Character {
1318/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1319/// Some(self.health.cmp(&other.health))
1320/// }
1321/// }
1322///
1323/// let a = Character {
1324/// health: 10,
1325/// experience: 5,
1326/// };
1327/// let b = Character {
1328/// health: 10,
1329/// experience: 77,
1330/// };
1331///
1332/// // Mistake: `PartialEq` and `PartialOrd` disagree with each other.
1333///
1334/// assert_eq!(a.partial_cmp(&b).unwrap(), Ordering::Equal); // a == b according to `PartialOrd`.
1335/// assert_ne!(a, b); // a != b according to `PartialEq`.
1336/// ```
1337///
1338/// # Examples
1339///
1340/// ```
1341/// let x: u32 = 0;
1342/// let y: u32 = 1;
1343///
1344/// assert_eq!(x < y, true);
1345/// assert_eq!(x.lt(&y), true);
1346/// ```
1347///
1348/// [`partial_cmp`]: PartialOrd::partial_cmp
1349/// [`cmp`]: Ord::cmp
1350#[lang = "partial_ord"]
1351#[stable(feature = "rust1", since = "1.0.0")]
1352#[doc(alias = ">")]
1353#[doc(alias = "<")]
1354#[doc(alias = "<=")]
1355#[doc(alias = ">=")]
1356#[rustc_on_unimplemented(
1357 message = "can't compare `{Self}` with `{Rhs}`",
1358 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
1359 append_const_msg
1360)]
1361#[rustc_diagnostic_item = "PartialOrd"]
1362#[allow(multiple_supertrait_upcastable)] // FIXME(sized_hierarchy): remove this
1363#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1364pub const trait PartialOrd<Rhs: PointeeSized = Self>:
1365 [const] PartialEq<Rhs> + PointeeSized
1366{
1367 /// This method returns an ordering between `self` and `other` values if one exists.
1368 ///
1369 /// # Examples
1370 ///
1371 /// ```
1372 /// use std::cmp::Ordering;
1373 ///
1374 /// let result = 1.0.partial_cmp(&2.0);
1375 /// assert_eq!(result, Some(Ordering::Less));
1376 ///
1377 /// let result = 1.0.partial_cmp(&1.0);
1378 /// assert_eq!(result, Some(Ordering::Equal));
1379 ///
1380 /// let result = 2.0.partial_cmp(&1.0);
1381 /// assert_eq!(result, Some(Ordering::Greater));
1382 /// ```
1383 ///
1384 /// When comparison is impossible:
1385 ///
1386 /// ```
1387 /// let result = f64::NAN.partial_cmp(&1.0);
1388 /// assert_eq!(result, None);
1389 /// ```
1390 #[must_use]
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 #[rustc_diagnostic_item = "cmp_partialord_cmp"]
1393 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1394
1395 /// Tests less than (for `self` and `other`) and is used by the `<` operator.
1396 ///
1397 /// # Examples
1398 ///
1399 /// ```
1400 /// assert_eq!(1.0 < 1.0, false);
1401 /// assert_eq!(1.0 < 2.0, true);
1402 /// assert_eq!(2.0 < 1.0, false);
1403 /// ```
1404 #[inline]
1405 #[must_use]
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 #[rustc_diagnostic_item = "cmp_partialord_lt"]
1408 fn lt(&self, other: &Rhs) -> bool {
1409 self.partial_cmp(other).is_some_and(Ordering::is_lt)
1410 }
1411
1412 /// Tests less than or equal to (for `self` and `other`) and is used by the
1413 /// `<=` operator.
1414 ///
1415 /// # Examples
1416 ///
1417 /// ```
1418 /// assert_eq!(1.0 <= 1.0, true);
1419 /// assert_eq!(1.0 <= 2.0, true);
1420 /// assert_eq!(2.0 <= 1.0, false);
1421 /// ```
1422 #[inline]
1423 #[must_use]
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 #[rustc_diagnostic_item = "cmp_partialord_le"]
1426 fn le(&self, other: &Rhs) -> bool {
1427 self.partial_cmp(other).is_some_and(Ordering::is_le)
1428 }
1429
1430 /// Tests greater than (for `self` and `other`) and is used by the `>`
1431 /// operator.
1432 ///
1433 /// # Examples
1434 ///
1435 /// ```
1436 /// assert_eq!(1.0 > 1.0, false);
1437 /// assert_eq!(1.0 > 2.0, false);
1438 /// assert_eq!(2.0 > 1.0, true);
1439 /// ```
1440 #[inline]
1441 #[must_use]
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 #[rustc_diagnostic_item = "cmp_partialord_gt"]
1444 fn gt(&self, other: &Rhs) -> bool {
1445 self.partial_cmp(other).is_some_and(Ordering::is_gt)
1446 }
1447
1448 /// Tests greater than or equal to (for `self` and `other`) and is used by
1449 /// the `>=` operator.
1450 ///
1451 /// # Examples
1452 ///
1453 /// ```
1454 /// assert_eq!(1.0 >= 1.0, true);
1455 /// assert_eq!(1.0 >= 2.0, false);
1456 /// assert_eq!(2.0 >= 1.0, true);
1457 /// ```
1458 #[inline]
1459 #[must_use]
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 #[rustc_diagnostic_item = "cmp_partialord_ge"]
1462 fn ge(&self, other: &Rhs) -> bool {
1463 self.partial_cmp(other).is_some_and(Ordering::is_ge)
1464 }
1465
1466 /// If `self == other`, returns `ControlFlow::Continue(())`.
1467 /// Otherwise, returns `ControlFlow::Break(self < other)`.
1468 ///
1469 /// This is useful for chaining together calls when implementing a lexical
1470 /// `PartialOrd::lt`, as it allows types (like primitives) which can cheaply
1471 /// check `==` and `<` separately to do rather than needing to calculate
1472 /// (then optimize out) the three-way `Ordering` result.
1473 #[inline]
1474 // Added to improve the behaviour of tuples; not necessarily stabilization-track.
1475 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1476 #[doc(hidden)]
1477 fn __chaining_lt(&self, other: &Rhs) -> ControlFlow<bool> {
1478 default_chaining_impl(self, other, Ordering::is_lt)
1479 }
1480
1481 /// Same as `__chaining_lt`, but for `<=` instead of `<`.
1482 #[inline]
1483 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1484 #[doc(hidden)]
1485 fn __chaining_le(&self, other: &Rhs) -> ControlFlow<bool> {
1486 default_chaining_impl(self, other, Ordering::is_le)
1487 }
1488
1489 /// Same as `__chaining_lt`, but for `>` instead of `<`.
1490 #[inline]
1491 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1492 #[doc(hidden)]
1493 fn __chaining_gt(&self, other: &Rhs) -> ControlFlow<bool> {
1494 default_chaining_impl(self, other, Ordering::is_gt)
1495 }
1496
1497 /// Same as `__chaining_lt`, but for `>=` instead of `<`.
1498 #[inline]
1499 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1500 #[doc(hidden)]
1501 fn __chaining_ge(&self, other: &Rhs) -> ControlFlow<bool> {
1502 default_chaining_impl(self, other, Ordering::is_ge)
1503 }
1504}
1505
1506#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1507const fn default_chaining_impl<T, U>(
1508 lhs: &T,
1509 rhs: &U,
1510 p: impl [const] FnOnce(Ordering) -> bool + [const] Destruct,
1511) -> ControlFlow<bool>
1512where
1513 T: [const] PartialOrd<U> + PointeeSized,
1514 U: PointeeSized,
1515{
1516 // It's important that this only call `partial_cmp` once, not call `eq` then
1517 // one of the relational operators. We don't want to `bcmp`-then-`memcp` a
1518 // `String`, for example, or similarly for other data structures (#108157).
1519 match <T as PartialOrd<U>>::partial_cmp(lhs, rhs) {
1520 Some(Equal) => ControlFlow::Continue(()),
1521 Some(c) => ControlFlow::Break(p(c)),
1522 None => ControlFlow::Break(false),
1523 }
1524}
1525
1526/// Derive macro generating an impl of the trait [`PartialOrd`].
1527/// The behavior of this macro is described in detail [here](PartialOrd#derivable).
1528#[rustc_builtin_macro]
1529#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1530#[allow_internal_unstable(core_intrinsics)]
1531#[cfg(not(feature = "ferrocene_certified"))]
1532pub macro PartialOrd($item:item) {
1533 /* compiler built-in */
1534}
1535
1536/// Compares and returns the minimum of two values.
1537///
1538/// Returns the first argument if the comparison determines them to be equal.
1539///
1540/// Internally uses an alias to [`Ord::min`].
1541///
1542/// # Examples
1543///
1544/// ```
1545/// use std::cmp;
1546///
1547/// assert_eq!(cmp::min(1, 2), 1);
1548/// assert_eq!(cmp::min(2, 2), 2);
1549/// ```
1550/// ```
1551/// use std::cmp::{self, Ordering};
1552///
1553/// #[derive(Eq)]
1554/// struct Equal(&'static str);
1555///
1556/// impl PartialEq for Equal {
1557/// fn eq(&self, other: &Self) -> bool { true }
1558/// }
1559/// impl PartialOrd for Equal {
1560/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1561/// }
1562/// impl Ord for Equal {
1563/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1564/// }
1565///
1566/// assert_eq!(cmp::min(Equal("v1"), Equal("v2")).0, "v1");
1567/// ```
1568#[inline]
1569#[must_use]
1570#[stable(feature = "rust1", since = "1.0.0")]
1571#[rustc_diagnostic_item = "cmp_min"]
1572#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1573pub const fn min<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1574 v1.min(v2)
1575}
1576
1577/// Returns the minimum of two values with respect to the specified comparison function.
1578///
1579/// Returns the first argument if the comparison determines them to be equal.
1580///
1581/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1582/// always passed as the first argument and `v2` as the second.
1583///
1584/// # Examples
1585///
1586/// ```
1587/// use std::cmp;
1588///
1589/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1590///
1591/// let result = cmp::min_by(2, -1, abs_cmp);
1592/// assert_eq!(result, -1);
1593///
1594/// let result = cmp::min_by(2, -3, abs_cmp);
1595/// assert_eq!(result, 2);
1596///
1597/// let result = cmp::min_by(1, -1, abs_cmp);
1598/// assert_eq!(result, 1);
1599/// ```
1600#[inline]
1601#[must_use]
1602#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1603#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1604#[cfg(not(feature = "ferrocene_certified"))]
1605pub const fn min_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1606 v1: T,
1607 v2: T,
1608 compare: F,
1609) -> T {
1610 if compare(&v1, &v2).is_le() { v1 } else { v2 }
1611}
1612
1613/// Returns the element that gives the minimum value from the specified function.
1614///
1615/// Returns the first argument if the comparison determines them to be equal.
1616///
1617/// # Examples
1618///
1619/// ```
1620/// use std::cmp;
1621///
1622/// let result = cmp::min_by_key(2, -1, |x: &i32| x.abs());
1623/// assert_eq!(result, -1);
1624///
1625/// let result = cmp::min_by_key(2, -3, |x: &i32| x.abs());
1626/// assert_eq!(result, 2);
1627///
1628/// let result = cmp::min_by_key(1, -1, |x: &i32| x.abs());
1629/// assert_eq!(result, 1);
1630/// ```
1631#[inline]
1632#[must_use]
1633#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1634#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1635#[cfg(not(feature = "ferrocene_certified"))]
1636pub const fn min_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1637where
1638 T: [const] Destruct,
1639 F: [const] FnMut(&T) -> K + [const] Destruct,
1640 K: [const] Ord + [const] Destruct,
1641{
1642 if f(&v2) < f(&v1) { v2 } else { v1 }
1643}
1644
1645/// Compares and returns the maximum of two values.
1646///
1647/// Returns the second argument if the comparison determines them to be equal.
1648///
1649/// Internally uses an alias to [`Ord::max`].
1650///
1651/// # Examples
1652///
1653/// ```
1654/// use std::cmp;
1655///
1656/// assert_eq!(cmp::max(1, 2), 2);
1657/// assert_eq!(cmp::max(2, 2), 2);
1658/// ```
1659/// ```
1660/// use std::cmp::{self, Ordering};
1661///
1662/// #[derive(Eq)]
1663/// struct Equal(&'static str);
1664///
1665/// impl PartialEq for Equal {
1666/// fn eq(&self, other: &Self) -> bool { true }
1667/// }
1668/// impl PartialOrd for Equal {
1669/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1670/// }
1671/// impl Ord for Equal {
1672/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1673/// }
1674///
1675/// assert_eq!(cmp::max(Equal("v1"), Equal("v2")).0, "v2");
1676/// ```
1677#[inline]
1678#[must_use]
1679#[stable(feature = "rust1", since = "1.0.0")]
1680#[rustc_diagnostic_item = "cmp_max"]
1681#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1682pub const fn max<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1683 v1.max(v2)
1684}
1685
1686/// Returns the maximum of two values with respect to the specified comparison function.
1687///
1688/// Returns the second argument if the comparison determines them to be equal.
1689///
1690/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1691/// always passed as the first argument and `v2` as the second.
1692///
1693/// # Examples
1694///
1695/// ```
1696/// use std::cmp;
1697///
1698/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1699///
1700/// let result = cmp::max_by(3, -2, abs_cmp) ;
1701/// assert_eq!(result, 3);
1702///
1703/// let result = cmp::max_by(1, -2, abs_cmp);
1704/// assert_eq!(result, -2);
1705///
1706/// let result = cmp::max_by(1, -1, abs_cmp);
1707/// assert_eq!(result, -1);
1708/// ```
1709#[inline]
1710#[must_use]
1711#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1712#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1713#[cfg(not(feature = "ferrocene_certified"))]
1714pub const fn max_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1715 v1: T,
1716 v2: T,
1717 compare: F,
1718) -> T {
1719 if compare(&v1, &v2).is_gt() { v1 } else { v2 }
1720}
1721
1722/// Returns the element that gives the maximum value from the specified function.
1723///
1724/// Returns the second argument if the comparison determines them to be equal.
1725///
1726/// # Examples
1727///
1728/// ```
1729/// use std::cmp;
1730///
1731/// let result = cmp::max_by_key(3, -2, |x: &i32| x.abs());
1732/// assert_eq!(result, 3);
1733///
1734/// let result = cmp::max_by_key(1, -2, |x: &i32| x.abs());
1735/// assert_eq!(result, -2);
1736///
1737/// let result = cmp::max_by_key(1, -1, |x: &i32| x.abs());
1738/// assert_eq!(result, -1);
1739/// ```
1740#[inline]
1741#[must_use]
1742#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1743#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1744#[cfg(not(feature = "ferrocene_certified"))]
1745pub const fn max_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1746where
1747 T: [const] Destruct,
1748 F: [const] FnMut(&T) -> K + [const] Destruct,
1749 K: [const] Ord + [const] Destruct,
1750{
1751 if f(&v2) < f(&v1) { v1 } else { v2 }
1752}
1753
1754/// Compares and sorts two values, returning minimum and maximum.
1755///
1756/// Returns `[v1, v2]` if the comparison determines them to be equal.
1757///
1758/// # Examples
1759///
1760/// ```
1761/// #![feature(cmp_minmax)]
1762/// use std::cmp;
1763///
1764/// assert_eq!(cmp::minmax(1, 2), [1, 2]);
1765/// assert_eq!(cmp::minmax(2, 1), [1, 2]);
1766///
1767/// // You can destructure the result using array patterns
1768/// let [min, max] = cmp::minmax(42, 17);
1769/// assert_eq!(min, 17);
1770/// assert_eq!(max, 42);
1771/// ```
1772/// ```
1773/// #![feature(cmp_minmax)]
1774/// use std::cmp::{self, Ordering};
1775///
1776/// #[derive(Eq)]
1777/// struct Equal(&'static str);
1778///
1779/// impl PartialEq for Equal {
1780/// fn eq(&self, other: &Self) -> bool { true }
1781/// }
1782/// impl PartialOrd for Equal {
1783/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1784/// }
1785/// impl Ord for Equal {
1786/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1787/// }
1788///
1789/// assert_eq!(cmp::minmax(Equal("v1"), Equal("v2")).map(|v| v.0), ["v1", "v2"]);
1790/// ```
1791#[inline]
1792#[must_use]
1793#[unstable(feature = "cmp_minmax", issue = "115939")]
1794#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1795#[cfg(not(feature = "ferrocene_certified"))]
1796pub const fn minmax<T>(v1: T, v2: T) -> [T; 2]
1797where
1798 T: [const] Ord,
1799{
1800 if v2 < v1 { [v2, v1] } else { [v1, v2] }
1801}
1802
1803/// Returns minimum and maximum values with respect to the specified comparison function.
1804///
1805/// Returns `[v1, v2]` if the comparison determines them to be equal.
1806///
1807/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1808/// always passed as the first argument and `v2` as the second.
1809///
1810/// # Examples
1811///
1812/// ```
1813/// #![feature(cmp_minmax)]
1814/// use std::cmp;
1815///
1816/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1817///
1818/// assert_eq!(cmp::minmax_by(-2, 1, abs_cmp), [1, -2]);
1819/// assert_eq!(cmp::minmax_by(-1, 2, abs_cmp), [-1, 2]);
1820/// assert_eq!(cmp::minmax_by(-2, 2, abs_cmp), [-2, 2]);
1821///
1822/// // You can destructure the result using array patterns
1823/// let [min, max] = cmp::minmax_by(-42, 17, abs_cmp);
1824/// assert_eq!(min, 17);
1825/// assert_eq!(max, -42);
1826/// ```
1827#[inline]
1828#[must_use]
1829#[unstable(feature = "cmp_minmax", issue = "115939")]
1830#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1831#[cfg(not(feature = "ferrocene_certified"))]
1832pub const fn minmax_by<T, F>(v1: T, v2: T, compare: F) -> [T; 2]
1833where
1834 F: [const] FnOnce(&T, &T) -> Ordering,
1835{
1836 if compare(&v1, &v2).is_le() { [v1, v2] } else { [v2, v1] }
1837}
1838
1839/// Returns minimum and maximum values with respect to the specified key function.
1840///
1841/// Returns `[v1, v2]` if the comparison determines them to be equal.
1842///
1843/// # Examples
1844///
1845/// ```
1846/// #![feature(cmp_minmax)]
1847/// use std::cmp;
1848///
1849/// assert_eq!(cmp::minmax_by_key(-2, 1, |x: &i32| x.abs()), [1, -2]);
1850/// assert_eq!(cmp::minmax_by_key(-2, 2, |x: &i32| x.abs()), [-2, 2]);
1851///
1852/// // You can destructure the result using array patterns
1853/// let [min, max] = cmp::minmax_by_key(-42, 17, |x: &i32| x.abs());
1854/// assert_eq!(min, 17);
1855/// assert_eq!(max, -42);
1856/// ```
1857#[inline]
1858#[must_use]
1859#[unstable(feature = "cmp_minmax", issue = "115939")]
1860#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1861#[cfg(not(feature = "ferrocene_certified"))]
1862pub const fn minmax_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> [T; 2]
1863where
1864 F: [const] FnMut(&T) -> K + [const] Destruct,
1865 K: [const] Ord + [const] Destruct,
1866{
1867 if f(&v2) < f(&v1) { [v2, v1] } else { [v1, v2] }
1868}
1869
1870// Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1871mod impls {
1872 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1873 use crate::hint::unreachable_unchecked;
1874 use crate::marker::PointeeSized;
1875 use crate::ops::ControlFlow::{self, Break, Continue};
1876
1877 macro_rules! partial_eq_impl {
1878 ($($t:ty)*) => ($(
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1881 impl const PartialEq for $t {
1882 #[inline]
1883 fn eq(&self, other: &Self) -> bool { *self == *other }
1884 #[inline]
1885 fn ne(&self, other: &Self) -> bool { *self != *other }
1886 }
1887 )*)
1888 }
1889
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1892 impl const PartialEq for () {
1893 #[inline]
1894 fn eq(&self, _other: &()) -> bool {
1895 true
1896 }
1897 #[inline]
1898 fn ne(&self, _other: &()) -> bool {
1899 false
1900 }
1901 }
1902
1903 partial_eq_impl! {
1904 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128
1905 }
1906
1907 macro_rules! eq_impl {
1908 ($($t:ty)*) => ($(
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1911 impl const Eq for $t {}
1912 )*)
1913 }
1914
1915 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1916
1917 #[rustfmt::skip]
1918 macro_rules! partial_ord_methods_primitive_impl {
1919 () => {
1920 #[inline(always)]
1921 fn lt(&self, other: &Self) -> bool { *self < *other }
1922 #[inline(always)]
1923 fn le(&self, other: &Self) -> bool { *self <= *other }
1924 #[inline(always)]
1925 fn gt(&self, other: &Self) -> bool { *self > *other }
1926 #[inline(always)]
1927 fn ge(&self, other: &Self) -> bool { *self >= *other }
1928
1929 // These implementations are the same for `Ord` or `PartialOrd` types
1930 // because if either is NAN the `==` test will fail so we end up in
1931 // the `Break` case and the comparison will correctly return `false`.
1932
1933 #[inline]
1934 fn __chaining_lt(&self, other: &Self) -> ControlFlow<bool> {
1935 let (lhs, rhs) = (*self, *other);
1936 if lhs == rhs { Continue(()) } else { Break(lhs < rhs) }
1937 }
1938 #[inline]
1939 fn __chaining_le(&self, other: &Self) -> ControlFlow<bool> {
1940 let (lhs, rhs) = (*self, *other);
1941 if lhs == rhs { Continue(()) } else { Break(lhs <= rhs) }
1942 }
1943 #[inline]
1944 fn __chaining_gt(&self, other: &Self) -> ControlFlow<bool> {
1945 let (lhs, rhs) = (*self, *other);
1946 if lhs == rhs { Continue(()) } else { Break(lhs > rhs) }
1947 }
1948 #[inline]
1949 fn __chaining_ge(&self, other: &Self) -> ControlFlow<bool> {
1950 let (lhs, rhs) = (*self, *other);
1951 if lhs == rhs { Continue(()) } else { Break(lhs >= rhs) }
1952 }
1953 };
1954 }
1955
1956 macro_rules! partial_ord_impl {
1957 ($($t:ty)*) => ($(
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1960 impl const PartialOrd for $t {
1961 #[inline]
1962 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1963 match (*self <= *other, *self >= *other) {
1964 (false, false) => None,
1965 (false, true) => Some(Greater),
1966 (true, false) => Some(Less),
1967 (true, true) => Some(Equal),
1968 }
1969 }
1970
1971 partial_ord_methods_primitive_impl!();
1972 }
1973 )*)
1974 }
1975
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1978 impl const PartialOrd for () {
1979 #[inline]
1980 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1981 Some(Equal)
1982 }
1983 }
1984
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1987 impl const PartialOrd for bool {
1988 #[inline]
1989 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1990 Some(self.cmp(other))
1991 }
1992
1993 partial_ord_methods_primitive_impl!();
1994 }
1995
1996 partial_ord_impl! { f16 f32 f64 f128 }
1997
1998 macro_rules! ord_impl {
1999 ($($t:ty)*) => ($(
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2002 impl const PartialOrd for $t {
2003 #[inline]
2004 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2005 Some(crate::intrinsics::three_way_compare(*self, *other))
2006 }
2007
2008 partial_ord_methods_primitive_impl!();
2009 }
2010
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2013 impl const Ord for $t {
2014 #[inline]
2015 fn cmp(&self, other: &Self) -> Ordering {
2016 crate::intrinsics::three_way_compare(*self, *other)
2017 }
2018 }
2019 )*)
2020 }
2021
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2024 impl const Ord for () {
2025 #[inline]
2026 fn cmp(&self, _other: &()) -> Ordering {
2027 Equal
2028 }
2029 }
2030
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2033 impl const Ord for bool {
2034 #[inline]
2035 fn cmp(&self, other: &bool) -> Ordering {
2036 // Casting to i8's and converting the difference to an Ordering generates
2037 // more optimal assembly.
2038 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
2039 match (*self as i8) - (*other as i8) {
2040 -1 => Less,
2041 0 => Equal,
2042 1 => Greater,
2043 #[ferrocene::annotation(
2044 "This match arm cannot be covered because it is unreachable. See the safety comment below."
2045 )]
2046 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
2047 _ => unsafe { unreachable_unchecked() },
2048 }
2049 }
2050
2051 #[inline]
2052 fn min(self, other: bool) -> bool {
2053 self & other
2054 }
2055
2056 #[inline]
2057 fn max(self, other: bool) -> bool {
2058 self | other
2059 }
2060
2061 #[inline]
2062 fn clamp(self, min: bool, max: bool) -> bool {
2063 assert!(min <= max);
2064 self.max(min).min(max)
2065 }
2066 }
2067
2068 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
2069
2070 #[unstable(feature = "never_type", issue = "35121")]
2071 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2072 impl const PartialEq for ! {
2073 #[inline]
2074 fn eq(&self, _: &!) -> bool {
2075 *self
2076 }
2077 }
2078
2079 #[unstable(feature = "never_type", issue = "35121")]
2080 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2081 impl const Eq for ! {}
2082
2083 #[unstable(feature = "never_type", issue = "35121")]
2084 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2085 impl const PartialOrd for ! {
2086 #[inline]
2087 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
2088 *self
2089 }
2090 }
2091
2092 #[unstable(feature = "never_type", issue = "35121")]
2093 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2094 impl const Ord for ! {
2095 #[inline]
2096 fn cmp(&self, _: &!) -> Ordering {
2097 *self
2098 }
2099 }
2100
2101 // & pointers
2102
2103 #[stable(feature = "rust1", since = "1.0.0")]
2104 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2105 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &A
2106 where
2107 A: [const] PartialEq<B>,
2108 {
2109 #[inline]
2110 fn eq(&self, other: &&B) -> bool {
2111 PartialEq::eq(*self, *other)
2112 }
2113 #[inline]
2114 fn ne(&self, other: &&B) -> bool {
2115 PartialEq::ne(*self, *other)
2116 }
2117 }
2118 #[stable(feature = "rust1", since = "1.0.0")]
2119 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2120 #[cfg(not(feature = "ferrocene_certified"))]
2121 impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&B> for &A
2122 where
2123 A: [const] PartialOrd<B>,
2124 {
2125 #[inline]
2126 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
2127 PartialOrd::partial_cmp(*self, *other)
2128 }
2129 #[inline]
2130 fn lt(&self, other: &&B) -> bool {
2131 PartialOrd::lt(*self, *other)
2132 }
2133 #[inline]
2134 fn le(&self, other: &&B) -> bool {
2135 PartialOrd::le(*self, *other)
2136 }
2137 #[inline]
2138 fn gt(&self, other: &&B) -> bool {
2139 PartialOrd::gt(*self, *other)
2140 }
2141 #[inline]
2142 fn ge(&self, other: &&B) -> bool {
2143 PartialOrd::ge(*self, *other)
2144 }
2145 #[inline]
2146 fn __chaining_lt(&self, other: &&B) -> ControlFlow<bool> {
2147 PartialOrd::__chaining_lt(*self, *other)
2148 }
2149 #[inline]
2150 fn __chaining_le(&self, other: &&B) -> ControlFlow<bool> {
2151 PartialOrd::__chaining_le(*self, *other)
2152 }
2153 #[inline]
2154 fn __chaining_gt(&self, other: &&B) -> ControlFlow<bool> {
2155 PartialOrd::__chaining_gt(*self, *other)
2156 }
2157 #[inline]
2158 fn __chaining_ge(&self, other: &&B) -> ControlFlow<bool> {
2159 PartialOrd::__chaining_ge(*self, *other)
2160 }
2161 }
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2164 #[cfg(not(feature = "ferrocene_certified"))]
2165 impl<A: PointeeSized> const Ord for &A
2166 where
2167 A: [const] Ord,
2168 {
2169 #[inline]
2170 fn cmp(&self, other: &Self) -> Ordering {
2171 Ord::cmp(*self, *other)
2172 }
2173 }
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2176 impl<A: PointeeSized> const Eq for &A where A: [const] Eq {}
2177
2178 // &mut pointers
2179
2180 #[stable(feature = "rust1", since = "1.0.0")]
2181 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2182 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &mut A
2183 where
2184 A: [const] PartialEq<B>,
2185 {
2186 #[inline]
2187 fn eq(&self, other: &&mut B) -> bool {
2188 PartialEq::eq(*self, *other)
2189 }
2190 #[inline]
2191 fn ne(&self, other: &&mut B) -> bool {
2192 PartialEq::ne(*self, *other)
2193 }
2194 }
2195 #[stable(feature = "rust1", since = "1.0.0")]
2196 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2197 #[cfg(not(feature = "ferrocene_certified"))]
2198 impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&mut B> for &mut A
2199 where
2200 A: [const] PartialOrd<B>,
2201 {
2202 #[inline]
2203 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
2204 PartialOrd::partial_cmp(*self, *other)
2205 }
2206 #[inline]
2207 fn lt(&self, other: &&mut B) -> bool {
2208 PartialOrd::lt(*self, *other)
2209 }
2210 #[inline]
2211 fn le(&self, other: &&mut B) -> bool {
2212 PartialOrd::le(*self, *other)
2213 }
2214 #[inline]
2215 fn gt(&self, other: &&mut B) -> bool {
2216 PartialOrd::gt(*self, *other)
2217 }
2218 #[inline]
2219 fn ge(&self, other: &&mut B) -> bool {
2220 PartialOrd::ge(*self, *other)
2221 }
2222 #[inline]
2223 fn __chaining_lt(&self, other: &&mut B) -> ControlFlow<bool> {
2224 PartialOrd::__chaining_lt(*self, *other)
2225 }
2226 #[inline]
2227 fn __chaining_le(&self, other: &&mut B) -> ControlFlow<bool> {
2228 PartialOrd::__chaining_le(*self, *other)
2229 }
2230 #[inline]
2231 fn __chaining_gt(&self, other: &&mut B) -> ControlFlow<bool> {
2232 PartialOrd::__chaining_gt(*self, *other)
2233 }
2234 #[inline]
2235 fn __chaining_ge(&self, other: &&mut B) -> ControlFlow<bool> {
2236 PartialOrd::__chaining_ge(*self, *other)
2237 }
2238 }
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2241 #[cfg(not(feature = "ferrocene_certified"))]
2242 impl<A: PointeeSized> const Ord for &mut A
2243 where
2244 A: [const] Ord,
2245 {
2246 #[inline]
2247 fn cmp(&self, other: &Self) -> Ordering {
2248 Ord::cmp(*self, *other)
2249 }
2250 }
2251 #[stable(feature = "rust1", since = "1.0.0")]
2252 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2253 impl<A: PointeeSized> const Eq for &mut A where A: [const] Eq {}
2254
2255 #[stable(feature = "rust1", since = "1.0.0")]
2256 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2257 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &A
2258 where
2259 A: [const] PartialEq<B>,
2260 {
2261 #[inline]
2262 fn eq(&self, other: &&mut B) -> bool {
2263 PartialEq::eq(*self, *other)
2264 }
2265 #[inline]
2266 fn ne(&self, other: &&mut B) -> bool {
2267 PartialEq::ne(*self, *other)
2268 }
2269 }
2270
2271 #[stable(feature = "rust1", since = "1.0.0")]
2272 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2273 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &mut A
2274 where
2275 A: [const] PartialEq<B>,
2276 {
2277 #[inline]
2278 fn eq(&self, other: &&B) -> bool {
2279 PartialEq::eq(*self, *other)
2280 }
2281 #[inline]
2282 fn ne(&self, other: &&B) -> bool {
2283 PartialEq::ne(*self, *other)
2284 }
2285 }
2286}