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