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