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