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")]
369pub struct AssertParamIsEq<T: Eq + PointeeSized> {
370 _field: crate::marker::PhantomData<T>,
371}
372
373/// An `Ordering` is the result of a comparison between two values.
374///
375/// # Examples
376///
377/// ```
378/// use std::cmp::Ordering;
379///
380/// assert_eq!(1.cmp(&2), Ordering::Less);
381///
382/// assert_eq!(1.cmp(&1), Ordering::Equal);
383///
384/// assert_eq!(2.cmp(&1), Ordering::Greater);
385/// ```
386#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Debug, Hash))]
387#[rustfmt::skip] // Ferrocene addition: avoid multi-line cfg_attr
388#[cfg_attr(not(feature = "ferrocene_certified"), derive_const(Clone, Eq, PartialOrd, Ord, PartialEq))]
389#[stable(feature = "rust1", since = "1.0.0")]
390// This is a lang item only so that `BinOp::Cmp` in MIR can return it.
391// It has no special behavior, but does require that the three variants
392// `Less`/`Equal`/`Greater` remain `-1_i8`/`0_i8`/`+1_i8` respectively.
393#[lang = "Ordering"]
394#[repr(i8)]
395pub enum Ordering {
396 /// An ordering where a compared value is less than another.
397 #[stable(feature = "rust1", since = "1.0.0")]
398 Less = -1,
399 /// An ordering where a compared value is equal to another.
400 #[stable(feature = "rust1", since = "1.0.0")]
401 Equal = 0,
402 /// An ordering where a compared value is greater than another.
403 #[stable(feature = "rust1", since = "1.0.0")]
404 Greater = 1,
405}
406
407impl Ordering {
408 #[inline]
409 const fn as_raw(self) -> i8 {
410 // FIXME(const-hack): just use `PartialOrd` against `Equal` once that's const
411 crate::intrinsics::discriminant_value(&self)
412 }
413
414 /// Returns `true` if the ordering is the `Equal` variant.
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// use std::cmp::Ordering;
420 ///
421 /// assert_eq!(Ordering::Less.is_eq(), false);
422 /// assert_eq!(Ordering::Equal.is_eq(), true);
423 /// assert_eq!(Ordering::Greater.is_eq(), false);
424 /// ```
425 #[inline]
426 #[must_use]
427 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
428 #[stable(feature = "ordering_helpers", since = "1.53.0")]
429 pub const fn is_eq(self) -> bool {
430 // All the `is_*` methods are implemented as comparisons against zero
431 // to follow how clang's libcxx implements their equivalents in
432 // <https://github.com/llvm/llvm-project/blob/60486292b79885b7800b082754153202bef5b1f0/libcxx/include/__compare/is_eq.h#L23-L28>
433
434 self.as_raw() == 0
435 }
436
437 /// Returns `true` if the ordering is not the `Equal` variant.
438 ///
439 /// # Examples
440 ///
441 /// ```
442 /// use std::cmp::Ordering;
443 ///
444 /// assert_eq!(Ordering::Less.is_ne(), true);
445 /// assert_eq!(Ordering::Equal.is_ne(), false);
446 /// assert_eq!(Ordering::Greater.is_ne(), true);
447 /// ```
448 #[inline]
449 #[must_use]
450 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
451 #[stable(feature = "ordering_helpers", since = "1.53.0")]
452 pub const fn is_ne(self) -> bool {
453 self.as_raw() != 0
454 }
455
456 /// Returns `true` if the ordering is the `Less` variant.
457 ///
458 /// # Examples
459 ///
460 /// ```
461 /// use std::cmp::Ordering;
462 ///
463 /// assert_eq!(Ordering::Less.is_lt(), true);
464 /// assert_eq!(Ordering::Equal.is_lt(), false);
465 /// assert_eq!(Ordering::Greater.is_lt(), false);
466 /// ```
467 #[inline]
468 #[must_use]
469 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
470 #[stable(feature = "ordering_helpers", since = "1.53.0")]
471 pub const fn is_lt(self) -> bool {
472 self.as_raw() < 0
473 }
474
475 /// Returns `true` if the ordering is the `Greater` variant.
476 ///
477 /// # Examples
478 ///
479 /// ```
480 /// use std::cmp::Ordering;
481 ///
482 /// assert_eq!(Ordering::Less.is_gt(), false);
483 /// assert_eq!(Ordering::Equal.is_gt(), false);
484 /// assert_eq!(Ordering::Greater.is_gt(), true);
485 /// ```
486 #[inline]
487 #[must_use]
488 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
489 #[stable(feature = "ordering_helpers", since = "1.53.0")]
490 pub const fn is_gt(self) -> bool {
491 self.as_raw() > 0
492 }
493
494 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// use std::cmp::Ordering;
500 ///
501 /// assert_eq!(Ordering::Less.is_le(), true);
502 /// assert_eq!(Ordering::Equal.is_le(), true);
503 /// assert_eq!(Ordering::Greater.is_le(), false);
504 /// ```
505 #[inline]
506 #[must_use]
507 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
508 #[stable(feature = "ordering_helpers", since = "1.53.0")]
509 pub const fn is_le(self) -> bool {
510 self.as_raw() <= 0
511 }
512
513 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
514 ///
515 /// # Examples
516 ///
517 /// ```
518 /// use std::cmp::Ordering;
519 ///
520 /// assert_eq!(Ordering::Less.is_ge(), false);
521 /// assert_eq!(Ordering::Equal.is_ge(), true);
522 /// assert_eq!(Ordering::Greater.is_ge(), true);
523 /// ```
524 #[inline]
525 #[must_use]
526 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
527 #[stable(feature = "ordering_helpers", since = "1.53.0")]
528 pub const fn is_ge(self) -> bool {
529 self.as_raw() >= 0
530 }
531
532 /// Reverses the `Ordering`.
533 ///
534 /// * `Less` becomes `Greater`.
535 /// * `Greater` becomes `Less`.
536 /// * `Equal` becomes `Equal`.
537 ///
538 /// # Examples
539 ///
540 /// Basic behavior:
541 ///
542 /// ```
543 /// use std::cmp::Ordering;
544 ///
545 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
546 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
547 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
548 /// ```
549 ///
550 /// This method can be used to reverse a comparison:
551 ///
552 /// ```
553 /// let data: &mut [_] = &mut [2, 10, 5, 8];
554 ///
555 /// // sort the array from largest to smallest.
556 /// data.sort_by(|a, b| a.cmp(b).reverse());
557 ///
558 /// let b: &mut [_] = &mut [10, 8, 5, 2];
559 /// assert!(data == b);
560 /// ```
561 #[inline]
562 #[must_use]
563 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub const fn reverse(self) -> Ordering {
566 match self {
567 Less => Greater,
568 Equal => Equal,
569 Greater => Less,
570 }
571 }
572
573 /// Chains two orderings.
574 ///
575 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// use std::cmp::Ordering;
581 ///
582 /// let result = Ordering::Equal.then(Ordering::Less);
583 /// assert_eq!(result, Ordering::Less);
584 ///
585 /// let result = Ordering::Less.then(Ordering::Equal);
586 /// assert_eq!(result, Ordering::Less);
587 ///
588 /// let result = Ordering::Less.then(Ordering::Greater);
589 /// assert_eq!(result, Ordering::Less);
590 ///
591 /// let result = Ordering::Equal.then(Ordering::Equal);
592 /// assert_eq!(result, Ordering::Equal);
593 ///
594 /// let x: (i64, i64, i64) = (1, 2, 7);
595 /// let y: (i64, i64, i64) = (1, 5, 3);
596 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
597 ///
598 /// assert_eq!(result, Ordering::Less);
599 /// ```
600 #[inline]
601 #[must_use]
602 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
603 #[stable(feature = "ordering_chaining", since = "1.17.0")]
604 pub const fn then(self, other: Ordering) -> Ordering {
605 match self {
606 Equal => other,
607 _ => self,
608 }
609 }
610
611 /// Chains the ordering with the given function.
612 ///
613 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
614 /// the result.
615 ///
616 /// # Examples
617 ///
618 /// ```
619 /// use std::cmp::Ordering;
620 ///
621 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
622 /// assert_eq!(result, Ordering::Less);
623 ///
624 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
625 /// assert_eq!(result, Ordering::Less);
626 ///
627 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
628 /// assert_eq!(result, Ordering::Less);
629 ///
630 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
631 /// assert_eq!(result, Ordering::Equal);
632 ///
633 /// let x: (i64, i64, i64) = (1, 2, 7);
634 /// let y: (i64, i64, i64) = (1, 5, 3);
635 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
636 ///
637 /// assert_eq!(result, Ordering::Less);
638 /// ```
639 #[inline]
640 #[must_use]
641 #[stable(feature = "ordering_chaining", since = "1.17.0")]
642 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
643 #[cfg(not(feature = "ferrocene_certified"))]
644 pub const fn then_with<F>(self, f: F) -> Ordering
645 where
646 F: [const] FnOnce() -> Ordering + [const] Destruct,
647 {
648 match self {
649 Equal => f(),
650 _ => self,
651 }
652 }
653}
654
655/// A helper struct for reverse ordering.
656///
657/// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
658/// can be used to reverse order a part of a key.
659///
660/// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
661///
662/// # Examples
663///
664/// ```
665/// use std::cmp::Reverse;
666///
667/// let mut v = vec![1, 2, 3, 4, 5, 6];
668/// v.sort_by_key(|&num| (num > 3, Reverse(num)));
669/// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
670/// ```
671#[derive(Copy, Debug, Hash)]
672#[derive_const(PartialEq, Eq, Default)]
673#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
674#[repr(transparent)]
675#[cfg(not(feature = "ferrocene_certified"))]
676pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
677
678#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
679#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
680#[cfg(not(feature = "ferrocene_certified"))]
681impl<T: [const] PartialOrd> const PartialOrd for Reverse<T> {
682 #[inline]
683 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
684 other.0.partial_cmp(&self.0)
685 }
686
687 #[inline]
688 fn lt(&self, other: &Self) -> bool {
689 other.0 < self.0
690 }
691 #[inline]
692 fn le(&self, other: &Self) -> bool {
693 other.0 <= self.0
694 }
695 #[inline]
696 fn gt(&self, other: &Self) -> bool {
697 other.0 > self.0
698 }
699 #[inline]
700 fn ge(&self, other: &Self) -> bool {
701 other.0 >= self.0
702 }
703}
704
705#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
706#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
707#[cfg(not(feature = "ferrocene_certified"))]
708impl<T: [const] Ord> const Ord for Reverse<T> {
709 #[inline]
710 fn cmp(&self, other: &Reverse<T>) -> Ordering {
711 other.0.cmp(&self.0)
712 }
713}
714
715#[stable(feature = "reverse_cmp_key", since = "1.19.0")]
716#[cfg(not(feature = "ferrocene_certified"))]
717impl<T: Clone> Clone for Reverse<T> {
718 #[inline]
719 fn clone(&self) -> Reverse<T> {
720 Reverse(self.0.clone())
721 }
722
723 #[inline]
724 fn clone_from(&mut self, source: &Self) {
725 self.0.clone_from(&source.0)
726 }
727}
728
729/// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
730///
731/// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure `max`,
732/// `min`, and `clamp` are consistent with `cmp`:
733///
734/// - `partial_cmp(a, b) == Some(cmp(a, b))`.
735/// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
736/// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
737/// - For `a.clamp(min, max)`, see the [method docs](#method.clamp) (ensured by the default
738/// implementation).
739///
740/// Violating these requirements is a logic error. The behavior resulting from a logic error is not
741/// specified, but users of the trait must ensure that such logic errors do *not* result in
742/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
743/// methods.
744///
745/// ## Corollaries
746///
747/// From the above and the requirements of `PartialOrd`, it follows that for all `a`, `b` and `c`:
748///
749/// - exactly one of `a < b`, `a == b` or `a > b` is true; and
750/// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and
751/// `>`.
752///
753/// Mathematically speaking, the `<` operator defines a strict [weak order]. In cases where `==`
754/// conforms to mathematical equality, it also defines a strict [total order].
755///
756/// [weak order]: https://en.wikipedia.org/wiki/Weak_ordering
757/// [total order]: https://en.wikipedia.org/wiki/Total_order
758///
759/// ## Derivable
760///
761/// This trait can be used with `#[derive]`.
762///
763/// When `derive`d on structs, it will produce a
764/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the
765/// top-to-bottom declaration order of the struct's members.
766///
767/// When `derive`d on enums, variants are ordered primarily by their discriminants. Secondarily,
768/// they are ordered by their fields. By default, the discriminant is smallest for variants at the
769/// top, and largest for variants at the bottom. Here's an example:
770///
771/// ```
772/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
773/// enum E {
774/// Top,
775/// Bottom,
776/// }
777///
778/// assert!(E::Top < E::Bottom);
779/// ```
780///
781/// However, manually setting the discriminants can override this default behavior:
782///
783/// ```
784/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
785/// enum E {
786/// Top = 2,
787/// Bottom = 1,
788/// }
789///
790/// assert!(E::Bottom < E::Top);
791/// ```
792///
793/// ## Lexicographical comparison
794///
795/// Lexicographical comparison is an operation with the following properties:
796/// - Two sequences are compared element by element.
797/// - The first mismatching element defines which sequence is lexicographically less or greater
798/// than the other.
799/// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than
800/// the other.
801/// - If two sequences have equivalent elements and are of the same length, then the sequences are
802/// lexicographically equal.
803/// - An empty sequence is lexicographically less than any non-empty sequence.
804/// - Two empty sequences are lexicographically equal.
805///
806/// ## How can I implement `Ord`?
807///
808/// `Ord` requires that the type also be [`PartialOrd`], [`PartialEq`], and [`Eq`].
809///
810/// Because `Ord` implies a stronger ordering relationship than [`PartialOrd`], and both `Ord` and
811/// [`PartialOrd`] must agree, you must choose how to implement `Ord` **first**. You can choose to
812/// derive it, or implement it manually. If you derive it, you should derive all four traits. If you
813/// implement it manually, you should manually implement all four traits, based on the
814/// implementation of `Ord`.
815///
816/// Here's an example where you want to define the `Character` comparison by `health` and
817/// `experience` only, disregarding the field `mana`:
818///
819/// ```
820/// use std::cmp::Ordering;
821///
822/// struct Character {
823/// health: u32,
824/// experience: u32,
825/// mana: f32,
826/// }
827///
828/// impl Ord for Character {
829/// fn cmp(&self, other: &Self) -> Ordering {
830/// self.experience
831/// .cmp(&other.experience)
832/// .then(self.health.cmp(&other.health))
833/// }
834/// }
835///
836/// impl PartialOrd for Character {
837/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
838/// Some(self.cmp(other))
839/// }
840/// }
841///
842/// impl PartialEq for Character {
843/// fn eq(&self, other: &Self) -> bool {
844/// self.health == other.health && self.experience == other.experience
845/// }
846/// }
847///
848/// impl Eq for Character {}
849/// ```
850///
851/// If all you need is to `slice::sort` a type by a field value, it can be simpler to use
852/// `slice::sort_by_key`.
853///
854/// ## Examples of incorrect `Ord` implementations
855///
856/// ```
857/// use std::cmp::Ordering;
858///
859/// #[derive(Debug)]
860/// struct Character {
861/// health: f32,
862/// }
863///
864/// impl Ord for Character {
865/// fn cmp(&self, other: &Self) -> std::cmp::Ordering {
866/// if self.health < other.health {
867/// Ordering::Less
868/// } else if self.health > other.health {
869/// Ordering::Greater
870/// } else {
871/// Ordering::Equal
872/// }
873/// }
874/// }
875///
876/// impl PartialOrd for Character {
877/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
878/// Some(self.cmp(other))
879/// }
880/// }
881///
882/// impl PartialEq for Character {
883/// fn eq(&self, other: &Self) -> bool {
884/// self.health == other.health
885/// }
886/// }
887///
888/// impl Eq for Character {}
889///
890/// let a = Character { health: 4.5 };
891/// let b = Character { health: f32::NAN };
892///
893/// // Mistake: floating-point values do not form a total order and using the built-in comparison
894/// // operands to implement `Ord` irregardless of that reality does not change it. Use
895/// // `f32::total_cmp` if you need a total order for floating-point values.
896///
897/// // Reflexivity requirement of `Ord` is not given.
898/// assert!(a == a);
899/// assert!(b != b);
900///
901/// // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be
902/// // true, not both or neither.
903/// assert_eq!((a < b) as u8 + (b < a) as u8, 0);
904/// ```
905///
906/// ```
907/// use std::cmp::Ordering;
908///
909/// #[derive(Debug)]
910/// struct Character {
911/// health: u32,
912/// experience: u32,
913/// }
914///
915/// impl PartialOrd for Character {
916/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
917/// Some(self.cmp(other))
918/// }
919/// }
920///
921/// impl Ord for Character {
922/// fn cmp(&self, other: &Self) -> std::cmp::Ordering {
923/// if self.health < 50 {
924/// self.health.cmp(&other.health)
925/// } else {
926/// self.experience.cmp(&other.experience)
927/// }
928/// }
929/// }
930///
931/// // For performance reasons implementing `PartialEq` this way is not the idiomatic way, but it
932/// // ensures consistent behavior between `PartialEq`, `PartialOrd` and `Ord` in this example.
933/// impl PartialEq for Character {
934/// fn eq(&self, other: &Self) -> bool {
935/// self.cmp(other) == Ordering::Equal
936/// }
937/// }
938///
939/// impl Eq for Character {}
940///
941/// let a = Character {
942/// health: 3,
943/// experience: 5,
944/// };
945/// let b = Character {
946/// health: 10,
947/// experience: 77,
948/// };
949/// let c = Character {
950/// health: 143,
951/// experience: 2,
952/// };
953///
954/// // Mistake: The implementation of `Ord` compares different fields depending on the value of
955/// // `self.health`, the resulting order is not total.
956///
957/// // Transitivity requirement of `Ord` is not given. If a is smaller than b and b is smaller than
958/// // c, by transitive property a must also be smaller than c.
959/// assert!(a < b && b < c && c < a);
960///
961/// // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be
962/// // true, not both or neither.
963/// assert_eq!((a < c) as u8 + (c < a) as u8, 2);
964/// ```
965///
966/// The documentation of [`PartialOrd`] contains further examples, for example it's wrong for
967/// [`PartialOrd`] and [`PartialEq`] to disagree.
968///
969/// [`cmp`]: Ord::cmp
970#[doc(alias = "<")]
971#[doc(alias = ">")]
972#[doc(alias = "<=")]
973#[doc(alias = ">=")]
974#[stable(feature = "rust1", since = "1.0.0")]
975#[rustc_diagnostic_item = "Ord"]
976#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
977pub const trait Ord: [const] Eq + [const] PartialOrd<Self> + PointeeSized {
978 /// This method returns an [`Ordering`] between `self` and `other`.
979 ///
980 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
981 /// `self <operator> other` if true.
982 ///
983 /// # Examples
984 ///
985 /// ```
986 /// use std::cmp::Ordering;
987 ///
988 /// assert_eq!(5.cmp(&10), Ordering::Less);
989 /// assert_eq!(10.cmp(&5), Ordering::Greater);
990 /// assert_eq!(5.cmp(&5), Ordering::Equal);
991 /// ```
992 #[must_use]
993 #[stable(feature = "rust1", since = "1.0.0")]
994 #[rustc_diagnostic_item = "ord_cmp_method"]
995 fn cmp(&self, other: &Self) -> Ordering;
996
997 /// Compares and returns the maximum of two values.
998 ///
999 /// Returns the second argument if the comparison determines them to be equal.
1000 ///
1001 /// # Examples
1002 ///
1003 /// ```
1004 /// assert_eq!(1.max(2), 2);
1005 /// assert_eq!(2.max(2), 2);
1006 /// ```
1007 /// ```
1008 /// use std::cmp::Ordering;
1009 ///
1010 /// #[derive(Eq)]
1011 /// struct Equal(&'static str);
1012 ///
1013 /// impl PartialEq for Equal {
1014 /// fn eq(&self, other: &Self) -> bool { true }
1015 /// }
1016 /// impl PartialOrd for Equal {
1017 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1018 /// }
1019 /// impl Ord for Equal {
1020 /// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1021 /// }
1022 ///
1023 /// assert_eq!(Equal("self").max(Equal("other")).0, "other");
1024 /// ```
1025 #[stable(feature = "ord_max_min", since = "1.21.0")]
1026 #[inline]
1027 #[must_use]
1028 #[rustc_diagnostic_item = "cmp_ord_max"]
1029 fn max(self, other: Self) -> Self
1030 where
1031 Self: Sized + [const] Destruct,
1032 {
1033 if other < self { self } else { other }
1034 }
1035
1036 /// Compares and returns the minimum of two values.
1037 ///
1038 /// Returns the first argument if the comparison determines them to be equal.
1039 ///
1040 /// # Examples
1041 ///
1042 /// ```
1043 /// assert_eq!(1.min(2), 1);
1044 /// assert_eq!(2.min(2), 2);
1045 /// ```
1046 /// ```
1047 /// use std::cmp::Ordering;
1048 ///
1049 /// #[derive(Eq)]
1050 /// struct Equal(&'static str);
1051 ///
1052 /// impl PartialEq for Equal {
1053 /// fn eq(&self, other: &Self) -> bool { true }
1054 /// }
1055 /// impl PartialOrd for Equal {
1056 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1057 /// }
1058 /// impl Ord for Equal {
1059 /// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1060 /// }
1061 ///
1062 /// assert_eq!(Equal("self").min(Equal("other")).0, "self");
1063 /// ```
1064 #[stable(feature = "ord_max_min", since = "1.21.0")]
1065 #[inline]
1066 #[must_use]
1067 #[rustc_diagnostic_item = "cmp_ord_min"]
1068 fn min(self, other: Self) -> Self
1069 where
1070 Self: Sized + [const] Destruct,
1071 {
1072 if other < self { other } else { self }
1073 }
1074
1075 /// Restrict a value to a certain interval.
1076 ///
1077 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1078 /// less than `min`. Otherwise this returns `self`.
1079 ///
1080 /// # Panics
1081 ///
1082 /// Panics if `min > max`.
1083 ///
1084 /// # Examples
1085 ///
1086 /// ```
1087 /// assert_eq!((-3).clamp(-2, 1), -2);
1088 /// assert_eq!(0.clamp(-2, 1), 0);
1089 /// assert_eq!(2.clamp(-2, 1), 1);
1090 /// ```
1091 #[must_use]
1092 #[inline]
1093 #[stable(feature = "clamp", since = "1.50.0")]
1094 fn clamp(self, min: Self, max: Self) -> Self
1095 where
1096 Self: Sized + [const] Destruct,
1097 {
1098 assert!(min <= max);
1099 if self < min {
1100 min
1101 } else if self > max {
1102 max
1103 } else {
1104 self
1105 }
1106 }
1107}
1108
1109/// Derive macro generating an impl of the trait [`Ord`].
1110/// The behavior of this macro is described in detail [here](Ord#derivable).
1111#[rustc_builtin_macro]
1112#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1113#[allow_internal_unstable(core_intrinsics)]
1114#[cfg(not(feature = "ferrocene_certified"))]
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::sqrt(-1.0);
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_certified"))]
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_certified"))]
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_certified"))]
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_certified"))]
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_certified"))]
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_certified"))]
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
1874 macro_rules! partial_eq_impl {
1875 ($($t:ty)*) => ($(
1876 #[stable(feature = "rust1", since = "1.0.0")]
1877 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1878 impl const PartialEq for $t {
1879 #[inline]
1880 fn eq(&self, other: &Self) -> bool { *self == *other }
1881 #[inline]
1882 fn ne(&self, other: &Self) -> bool { *self != *other }
1883 }
1884 )*)
1885 }
1886
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1889 impl const PartialEq for () {
1890 #[inline]
1891 fn eq(&self, _other: &()) -> bool {
1892 true
1893 }
1894 #[inline]
1895 fn ne(&self, _other: &()) -> bool {
1896 false
1897 }
1898 }
1899
1900 partial_eq_impl! {
1901 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128
1902 }
1903
1904 macro_rules! eq_impl {
1905 ($($t:ty)*) => ($(
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1908 impl const Eq for $t {}
1909 )*)
1910 }
1911
1912 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1913
1914 #[rustfmt::skip]
1915 macro_rules! partial_ord_methods_primitive_impl {
1916 () => {
1917 #[inline(always)]
1918 fn lt(&self, other: &Self) -> bool { *self < *other }
1919 #[inline(always)]
1920 fn le(&self, other: &Self) -> bool { *self <= *other }
1921 #[inline(always)]
1922 fn gt(&self, other: &Self) -> bool { *self > *other }
1923 #[inline(always)]
1924 fn ge(&self, other: &Self) -> bool { *self >= *other }
1925
1926 // These implementations are the same for `Ord` or `PartialOrd` types
1927 // because if either is NAN the `==` test will fail so we end up in
1928 // the `Break` case and the comparison will correctly return `false`.
1929
1930 #[inline]
1931 fn __chaining_lt(&self, other: &Self) -> ControlFlow<bool> {
1932 let (lhs, rhs) = (*self, *other);
1933 if lhs == rhs { Continue(()) } else { Break(lhs < rhs) }
1934 }
1935 #[inline]
1936 fn __chaining_le(&self, other: &Self) -> ControlFlow<bool> {
1937 let (lhs, rhs) = (*self, *other);
1938 if lhs == rhs { Continue(()) } else { Break(lhs <= rhs) }
1939 }
1940 #[inline]
1941 fn __chaining_gt(&self, other: &Self) -> ControlFlow<bool> {
1942 let (lhs, rhs) = (*self, *other);
1943 if lhs == rhs { Continue(()) } else { Break(lhs > rhs) }
1944 }
1945 #[inline]
1946 fn __chaining_ge(&self, other: &Self) -> ControlFlow<bool> {
1947 let (lhs, rhs) = (*self, *other);
1948 if lhs == rhs { Continue(()) } else { Break(lhs >= rhs) }
1949 }
1950 };
1951 }
1952
1953 macro_rules! partial_ord_impl {
1954 ($($t:ty)*) => ($(
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1957 impl const PartialOrd for $t {
1958 #[inline]
1959 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1960 match (*self <= *other, *self >= *other) {
1961 (false, false) => None,
1962 (false, true) => Some(Greater),
1963 (true, false) => Some(Less),
1964 (true, true) => Some(Equal),
1965 }
1966 }
1967
1968 partial_ord_methods_primitive_impl!();
1969 }
1970 )*)
1971 }
1972
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1975 impl const PartialOrd for () {
1976 #[inline]
1977 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1978 Some(Equal)
1979 }
1980 }
1981
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1984 impl const PartialOrd for bool {
1985 #[inline]
1986 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1987 Some(self.cmp(other))
1988 }
1989
1990 partial_ord_methods_primitive_impl!();
1991 }
1992
1993 partial_ord_impl! { f16 f32 f64 f128 }
1994
1995 macro_rules! ord_impl {
1996 ($($t:ty)*) => ($(
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1999 impl const PartialOrd for $t {
2000 #[inline]
2001 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2002 Some(crate::intrinsics::three_way_compare(*self, *other))
2003 }
2004
2005 partial_ord_methods_primitive_impl!();
2006 }
2007
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2010 impl const Ord for $t {
2011 #[inline]
2012 fn cmp(&self, other: &Self) -> Ordering {
2013 crate::intrinsics::three_way_compare(*self, *other)
2014 }
2015 }
2016 )*)
2017 }
2018
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2021 impl const Ord for () {
2022 #[inline]
2023 fn cmp(&self, _other: &()) -> Ordering {
2024 Equal
2025 }
2026 }
2027
2028 #[stable(feature = "rust1", since = "1.0.0")]
2029 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2030 impl const Ord for bool {
2031 #[inline]
2032 fn cmp(&self, other: &bool) -> Ordering {
2033 // Casting to i8's and converting the difference to an Ordering generates
2034 // more optimal assembly.
2035 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
2036 match (*self as i8) - (*other as i8) {
2037 -1 => Less,
2038 0 => Equal,
2039 1 => Greater,
2040 #[ferrocene::annotation(
2041 "This match arm cannot be covered because it is unreachable. See the safety comment below."
2042 )]
2043 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
2044 _ => unsafe { unreachable_unchecked() },
2045 }
2046 }
2047
2048 #[inline]
2049 fn min(self, other: bool) -> bool {
2050 self & other
2051 }
2052
2053 #[inline]
2054 fn max(self, other: bool) -> bool {
2055 self | other
2056 }
2057
2058 #[inline]
2059 fn clamp(self, min: bool, max: bool) -> bool {
2060 assert!(min <= max);
2061 self.max(min).min(max)
2062 }
2063 }
2064
2065 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
2066
2067 #[unstable(feature = "never_type", issue = "35121")]
2068 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2069 impl const PartialEq for ! {
2070 #[inline]
2071 fn eq(&self, _: &!) -> bool {
2072 *self
2073 }
2074 }
2075
2076 #[unstable(feature = "never_type", issue = "35121")]
2077 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2078 impl const Eq for ! {}
2079
2080 #[unstable(feature = "never_type", issue = "35121")]
2081 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2082 impl const PartialOrd for ! {
2083 #[inline]
2084 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
2085 *self
2086 }
2087 }
2088
2089 #[unstable(feature = "never_type", issue = "35121")]
2090 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2091 impl const Ord for ! {
2092 #[inline]
2093 fn cmp(&self, _: &!) -> Ordering {
2094 *self
2095 }
2096 }
2097
2098 // & pointers
2099
2100 #[stable(feature = "rust1", since = "1.0.0")]
2101 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2102 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &A
2103 where
2104 A: [const] PartialEq<B>,
2105 {
2106 #[inline]
2107 fn eq(&self, other: &&B) -> bool {
2108 PartialEq::eq(*self, *other)
2109 }
2110 #[inline]
2111 fn ne(&self, other: &&B) -> bool {
2112 PartialEq::ne(*self, *other)
2113 }
2114 }
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2117 impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&B> for &A
2118 where
2119 A: [const] PartialOrd<B>,
2120 {
2121 #[inline]
2122 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
2123 PartialOrd::partial_cmp(*self, *other)
2124 }
2125 #[inline]
2126 fn lt(&self, other: &&B) -> bool {
2127 PartialOrd::lt(*self, *other)
2128 }
2129 #[inline]
2130 fn le(&self, other: &&B) -> bool {
2131 PartialOrd::le(*self, *other)
2132 }
2133 #[inline]
2134 fn gt(&self, other: &&B) -> bool {
2135 PartialOrd::gt(*self, *other)
2136 }
2137 #[inline]
2138 fn ge(&self, other: &&B) -> bool {
2139 PartialOrd::ge(*self, *other)
2140 }
2141 #[inline]
2142 fn __chaining_lt(&self, other: &&B) -> ControlFlow<bool> {
2143 PartialOrd::__chaining_lt(*self, *other)
2144 }
2145 #[inline]
2146 fn __chaining_le(&self, other: &&B) -> ControlFlow<bool> {
2147 PartialOrd::__chaining_le(*self, *other)
2148 }
2149 #[inline]
2150 fn __chaining_gt(&self, other: &&B) -> ControlFlow<bool> {
2151 PartialOrd::__chaining_gt(*self, *other)
2152 }
2153 #[inline]
2154 fn __chaining_ge(&self, other: &&B) -> ControlFlow<bool> {
2155 PartialOrd::__chaining_ge(*self, *other)
2156 }
2157 }
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2160 #[cfg(not(feature = "ferrocene_certified"))]
2161 impl<A: PointeeSized> const Ord for &A
2162 where
2163 A: [const] Ord,
2164 {
2165 #[inline]
2166 fn cmp(&self, other: &Self) -> Ordering {
2167 Ord::cmp(*self, *other)
2168 }
2169 }
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2172 impl<A: PointeeSized> const Eq for &A where A: [const] Eq {}
2173
2174 // &mut pointers
2175
2176 #[stable(feature = "rust1", since = "1.0.0")]
2177 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2178 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &mut A
2179 where
2180 A: [const] PartialEq<B>,
2181 {
2182 #[inline]
2183 fn eq(&self, other: &&mut B) -> bool {
2184 PartialEq::eq(*self, *other)
2185 }
2186 #[inline]
2187 fn ne(&self, other: &&mut B) -> bool {
2188 PartialEq::ne(*self, *other)
2189 }
2190 }
2191 #[stable(feature = "rust1", since = "1.0.0")]
2192 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2193 #[cfg(not(feature = "ferrocene_certified"))]
2194 impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&mut B> for &mut A
2195 where
2196 A: [const] PartialOrd<B>,
2197 {
2198 #[inline]
2199 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
2200 PartialOrd::partial_cmp(*self, *other)
2201 }
2202 #[inline]
2203 fn lt(&self, other: &&mut B) -> bool {
2204 PartialOrd::lt(*self, *other)
2205 }
2206 #[inline]
2207 fn le(&self, other: &&mut B) -> bool {
2208 PartialOrd::le(*self, *other)
2209 }
2210 #[inline]
2211 fn gt(&self, other: &&mut B) -> bool {
2212 PartialOrd::gt(*self, *other)
2213 }
2214 #[inline]
2215 fn ge(&self, other: &&mut B) -> bool {
2216 PartialOrd::ge(*self, *other)
2217 }
2218 #[inline]
2219 fn __chaining_lt(&self, other: &&mut B) -> ControlFlow<bool> {
2220 PartialOrd::__chaining_lt(*self, *other)
2221 }
2222 #[inline]
2223 fn __chaining_le(&self, other: &&mut B) -> ControlFlow<bool> {
2224 PartialOrd::__chaining_le(*self, *other)
2225 }
2226 #[inline]
2227 fn __chaining_gt(&self, other: &&mut B) -> ControlFlow<bool> {
2228 PartialOrd::__chaining_gt(*self, *other)
2229 }
2230 #[inline]
2231 fn __chaining_ge(&self, other: &&mut B) -> ControlFlow<bool> {
2232 PartialOrd::__chaining_ge(*self, *other)
2233 }
2234 }
2235 #[stable(feature = "rust1", since = "1.0.0")]
2236 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2237 #[cfg(not(feature = "ferrocene_certified"))]
2238 impl<A: PointeeSized> const Ord for &mut A
2239 where
2240 A: [const] Ord,
2241 {
2242 #[inline]
2243 fn cmp(&self, other: &Self) -> Ordering {
2244 Ord::cmp(*self, *other)
2245 }
2246 }
2247 #[stable(feature = "rust1", since = "1.0.0")]
2248 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2249 impl<A: PointeeSized> const Eq for &mut A where A: [const] Eq {}
2250
2251 #[stable(feature = "rust1", since = "1.0.0")]
2252 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2253 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &A
2254 where
2255 A: [const] PartialEq<B>,
2256 {
2257 #[inline]
2258 fn eq(&self, other: &&mut B) -> bool {
2259 PartialEq::eq(*self, *other)
2260 }
2261 #[inline]
2262 fn ne(&self, other: &&mut B) -> bool {
2263 PartialEq::ne(*self, *other)
2264 }
2265 }
2266
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2269 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &mut A
2270 where
2271 A: [const] PartialEq<B>,
2272 {
2273 #[inline]
2274 fn eq(&self, other: &&B) -> bool {
2275 PartialEq::eq(*self, *other)
2276 }
2277 #[inline]
2278 fn ne(&self, other: &&B) -> bool {
2279 PartialEq::ne(*self, *other)
2280 }
2281 }
2282}