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