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