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