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 `ControlFlow::Continue(())`.
1582 /// Otherwise, returns `ControlFlow::Break(self < other)`.
1583 ///
1584 /// This is useful for chaining together calls when implementing a lexical
1585 /// `PartialOrd::lt`, as it allows types (like primitives) which can cheaply
1586 /// check `==` and `<` separately to do rather than needing to calculate
1587 /// (then optimize out) the three-way `Ordering` result.
1588 #[inline]
1589 // Added to improve the behaviour of tuples; not necessarily stabilization-track.
1590 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1591 #[doc(hidden)]
1592 #[ferrocene::prevalidated]
1593 fn __chaining_lt(&self, other: &Rhs) -> ControlFlow<bool> {
1594 default_chaining_impl(self, other, Ordering::is_lt)
1595 }
1596
1597 /// Same as `__chaining_lt`, but for `<=` instead of `<`.
1598 #[inline]
1599 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1600 #[doc(hidden)]
1601 #[ferrocene::prevalidated]
1602 fn __chaining_le(&self, other: &Rhs) -> ControlFlow<bool> {
1603 default_chaining_impl(self, other, Ordering::is_le)
1604 }
1605
1606 /// Same as `__chaining_lt`, but for `>` instead of `<`.
1607 #[inline]
1608 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1609 #[doc(hidden)]
1610 #[ferrocene::prevalidated]
1611 fn __chaining_gt(&self, other: &Rhs) -> ControlFlow<bool> {
1612 default_chaining_impl(self, other, Ordering::is_gt)
1613 }
1614
1615 /// Same as `__chaining_lt`, but for `>=` instead of `<`.
1616 #[inline]
1617 #[unstable(feature = "partial_ord_chaining_methods", issue = "none")]
1618 #[doc(hidden)]
1619 #[ferrocene::prevalidated]
1620 fn __chaining_ge(&self, other: &Rhs) -> ControlFlow<bool> {
1621 default_chaining_impl(self, other, Ordering::is_ge)
1622 }
1623}
1624
1625#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1626#[ferrocene::prevalidated]
1627const fn default_chaining_impl<T, U>(
1628 lhs: &T,
1629 rhs: &U,
1630 p: impl [const] FnOnce(Ordering) -> bool + [const] Destruct,
1631) -> ControlFlow<bool>
1632where
1633 T: [const] PartialOrd<U> + PointeeSized,
1634 U: PointeeSized,
1635{
1636 // It's important that this only call `partial_cmp` once, not call `eq` then
1637 // one of the relational operators. We don't want to `bcmp`-then-`memcp` a
1638 // `String`, for example, or similarly for other data structures (#108157).
1639 match <T as PartialOrd<U>>::partial_cmp(lhs, rhs) {
1640 Some(Equal) => ControlFlow::Continue(()),
1641 Some(c) => ControlFlow::Break(p(c)),
1642 None => ControlFlow::Break(false),
1643 }
1644}
1645
1646/// Derive macro generating an impl of the trait [`PartialOrd`].
1647/// The behavior of this macro is described in detail [here](PartialOrd#derivable).
1648#[rustc_builtin_macro]
1649#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1650#[allow_internal_unstable(core_intrinsics)]
1651pub macro PartialOrd($item:item) {
1652 /* compiler built-in */
1653}
1654
1655/// Compares and returns the minimum of two values.
1656///
1657/// Returns the first argument if the comparison determines them to be equal.
1658///
1659/// Internally uses an alias to [`Ord::min`].
1660///
1661/// # Examples
1662///
1663/// ```
1664/// use std::cmp;
1665///
1666/// assert_eq!(cmp::min(1, 2), 1);
1667/// assert_eq!(cmp::min(2, 2), 2);
1668/// ```
1669/// ```
1670/// use std::cmp::{self, Ordering};
1671///
1672/// #[derive(Eq)]
1673/// struct Equal(&'static str);
1674///
1675/// impl PartialEq for Equal {
1676/// fn eq(&self, other: &Self) -> bool { true }
1677/// }
1678/// impl PartialOrd for Equal {
1679/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1680/// }
1681/// impl Ord for Equal {
1682/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1683/// }
1684///
1685/// assert_eq!(cmp::min(Equal("v1"), Equal("v2")).0, "v1");
1686/// ```
1687#[inline]
1688#[must_use]
1689#[stable(feature = "rust1", since = "1.0.0")]
1690#[rustc_diagnostic_item = "cmp_min"]
1691#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1692#[ferrocene::prevalidated]
1693pub const fn min<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1694 v1.min(v2)
1695}
1696
1697/// Returns the minimum of two values with respect to the specified comparison function.
1698///
1699/// Returns the first argument if the comparison determines them to be equal.
1700///
1701/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1702/// always passed as the first argument and `v2` as the second.
1703///
1704/// # Examples
1705///
1706/// ```
1707/// use std::cmp;
1708///
1709/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1710///
1711/// let result = cmp::min_by(2, -1, abs_cmp);
1712/// assert_eq!(result, -1);
1713///
1714/// let result = cmp::min_by(2, -3, abs_cmp);
1715/// assert_eq!(result, 2);
1716///
1717/// let result = cmp::min_by(1, -1, abs_cmp);
1718/// assert_eq!(result, 1);
1719/// ```
1720#[inline]
1721#[must_use]
1722#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1723#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1724pub const fn min_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1725 v1: T,
1726 v2: T,
1727 compare: F,
1728) -> T {
1729 if compare(&v1, &v2).is_le() { v1 } else { v2 }
1730}
1731
1732/// Returns the element that gives the minimum value from the specified function.
1733///
1734/// Returns the first argument if the comparison determines them to be equal.
1735///
1736/// # Examples
1737///
1738/// ```
1739/// use std::cmp;
1740///
1741/// let result = cmp::min_by_key(2, -1, |x: &i32| x.abs());
1742/// assert_eq!(result, -1);
1743///
1744/// let result = cmp::min_by_key(2, -3, |x: &i32| x.abs());
1745/// assert_eq!(result, 2);
1746///
1747/// let result = cmp::min_by_key(1, -1, |x: &i32| x.abs());
1748/// assert_eq!(result, 1);
1749/// ```
1750#[inline]
1751#[must_use]
1752#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1753#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1754pub const fn min_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1755where
1756 T: [const] Destruct,
1757 F: [const] FnMut(&T) -> K + [const] Destruct,
1758 K: [const] Ord + [const] Destruct,
1759{
1760 if f(&v2) < f(&v1) { v2 } else { v1 }
1761}
1762
1763/// Compares and returns the maximum of two values.
1764///
1765/// Returns the second argument if the comparison determines them to be equal.
1766///
1767/// Internally uses an alias to [`Ord::max`].
1768///
1769/// # Examples
1770///
1771/// ```
1772/// use std::cmp;
1773///
1774/// assert_eq!(cmp::max(1, 2), 2);
1775/// assert_eq!(cmp::max(2, 2), 2);
1776/// ```
1777/// ```
1778/// use std::cmp::{self, Ordering};
1779///
1780/// #[derive(Eq)]
1781/// struct Equal(&'static str);
1782///
1783/// impl PartialEq for Equal {
1784/// fn eq(&self, other: &Self) -> bool { true }
1785/// }
1786/// impl PartialOrd for Equal {
1787/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1788/// }
1789/// impl Ord for Equal {
1790/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1791/// }
1792///
1793/// assert_eq!(cmp::max(Equal("v1"), Equal("v2")).0, "v2");
1794/// ```
1795#[inline]
1796#[must_use]
1797#[stable(feature = "rust1", since = "1.0.0")]
1798#[rustc_diagnostic_item = "cmp_max"]
1799#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1800#[ferrocene::prevalidated]
1801pub const fn max<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1802 v1.max(v2)
1803}
1804
1805/// Returns the maximum of two values with respect to the specified comparison function.
1806///
1807/// Returns the second argument if the comparison determines them to be equal.
1808///
1809/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1810/// always passed as the first argument and `v2` as the second.
1811///
1812/// # Examples
1813///
1814/// ```
1815/// use std::cmp;
1816///
1817/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1818///
1819/// let result = cmp::max_by(3, -2, abs_cmp) ;
1820/// assert_eq!(result, 3);
1821///
1822/// let result = cmp::max_by(1, -2, abs_cmp);
1823/// assert_eq!(result, -2);
1824///
1825/// let result = cmp::max_by(1, -1, abs_cmp);
1826/// assert_eq!(result, -1);
1827/// ```
1828#[inline]
1829#[must_use]
1830#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1831#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1832#[ferrocene::prevalidated]
1833pub const fn max_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1834 v1: T,
1835 v2: T,
1836 compare: F,
1837) -> T {
1838 if compare(&v1, &v2).is_gt() { v1 } else { v2 }
1839}
1840
1841/// Returns the element that gives the maximum value from the specified function.
1842///
1843/// Returns the second argument if the comparison determines them to be equal.
1844///
1845/// # Examples
1846///
1847/// ```
1848/// use std::cmp;
1849///
1850/// let result = cmp::max_by_key(3, -2, |x: &i32| x.abs());
1851/// assert_eq!(result, 3);
1852///
1853/// let result = cmp::max_by_key(1, -2, |x: &i32| x.abs());
1854/// assert_eq!(result, -2);
1855///
1856/// let result = cmp::max_by_key(1, -1, |x: &i32| x.abs());
1857/// assert_eq!(result, -1);
1858/// ```
1859#[inline]
1860#[must_use]
1861#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1862#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1863pub const fn max_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1864where
1865 T: [const] Destruct,
1866 F: [const] FnMut(&T) -> K + [const] Destruct,
1867 K: [const] Ord + [const] Destruct,
1868{
1869 if f(&v2) < f(&v1) { v1 } else { v2 }
1870}
1871
1872/// Compares and sorts two values, returning minimum and maximum.
1873///
1874/// Returns `[v1, v2]` if the comparison determines them to be equal.
1875///
1876/// # Examples
1877///
1878/// ```
1879/// #![feature(cmp_minmax)]
1880/// use std::cmp;
1881///
1882/// assert_eq!(cmp::minmax(1, 2), [1, 2]);
1883/// assert_eq!(cmp::minmax(2, 1), [1, 2]);
1884///
1885/// // You can destructure the result using array patterns
1886/// let [min, max] = cmp::minmax(42, 17);
1887/// assert_eq!(min, 17);
1888/// assert_eq!(max, 42);
1889/// ```
1890/// ```
1891/// #![feature(cmp_minmax)]
1892/// use std::cmp::{self, Ordering};
1893///
1894/// #[derive(Eq)]
1895/// struct Equal(&'static str);
1896///
1897/// impl PartialEq for Equal {
1898/// fn eq(&self, other: &Self) -> bool { true }
1899/// }
1900/// impl PartialOrd for Equal {
1901/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1902/// }
1903/// impl Ord for Equal {
1904/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1905/// }
1906///
1907/// assert_eq!(cmp::minmax(Equal("v1"), Equal("v2")).map(|v| v.0), ["v1", "v2"]);
1908/// ```
1909#[inline]
1910#[must_use]
1911#[unstable(feature = "cmp_minmax", issue = "115939")]
1912#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1913pub const fn minmax<T>(v1: T, v2: T) -> [T; 2]
1914where
1915 T: [const] Ord,
1916{
1917 if v2 < v1 { [v2, v1] } else { [v1, v2] }
1918}
1919
1920/// Returns minimum and maximum values with respect to the specified comparison function.
1921///
1922/// Returns `[v1, v2]` if the comparison determines them to be equal.
1923///
1924/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1925/// always passed as the first argument and `v2` as the second.
1926///
1927/// # Examples
1928///
1929/// ```
1930/// #![feature(cmp_minmax)]
1931/// use std::cmp;
1932///
1933/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1934///
1935/// assert_eq!(cmp::minmax_by(-2, 1, abs_cmp), [1, -2]);
1936/// assert_eq!(cmp::minmax_by(-1, 2, abs_cmp), [-1, 2]);
1937/// assert_eq!(cmp::minmax_by(-2, 2, abs_cmp), [-2, 2]);
1938///
1939/// // You can destructure the result using array patterns
1940/// let [min, max] = cmp::minmax_by(-42, 17, abs_cmp);
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<T, F>(v1: T, v2: T, compare: F) -> [T; 2]
1949where
1950 F: [const] FnOnce(&T, &T) -> Ordering,
1951{
1952 if compare(&v1, &v2).is_le() { [v1, v2] } else { [v2, v1] }
1953}
1954
1955/// Returns minimum and maximum values with respect to the specified key function.
1956///
1957/// Returns `[v1, v2]` if the comparison determines them to be equal.
1958///
1959/// # Examples
1960///
1961/// ```
1962/// #![feature(cmp_minmax)]
1963/// use std::cmp;
1964///
1965/// assert_eq!(cmp::minmax_by_key(-2, 1, |x: &i32| x.abs()), [1, -2]);
1966/// assert_eq!(cmp::minmax_by_key(-2, 2, |x: &i32| x.abs()), [-2, 2]);
1967///
1968/// // You can destructure the result using array patterns
1969/// let [min, max] = cmp::minmax_by_key(-42, 17, |x: &i32| x.abs());
1970/// assert_eq!(min, 17);
1971/// assert_eq!(max, -42);
1972/// ```
1973#[inline]
1974#[must_use]
1975#[unstable(feature = "cmp_minmax", issue = "115939")]
1976#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1977pub const fn minmax_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> [T; 2]
1978where
1979 F: [const] FnMut(&T) -> K + [const] Destruct,
1980 K: [const] Ord + [const] Destruct,
1981{
1982 if f(&v2) < f(&v1) { [v2, v1] } else { [v1, v2] }
1983}
1984
1985/// Calls `mac` on lists of arguments from size `0` to `1 + count($y)`.
1986macro impl_for_tuples_up_to($mac:ident! { $($x:ident, $($y:ident,)*)? }) {
1987 $(impl_for_tuples_up_to! {
1988 $mac! { $($y,)* }
1989 })?
1990 $mac! { $($x, $($y,)*)? }
1991}
1992
1993/// Calls each `mac` on lists of arguments from size zero to twelve.
1994macro impl_tuples($($mac:ident,)+) {
1995 $(impl_for_tuples_up_to! { $mac! { x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, } })+
1996}
1997
1998/// Implementation detail for [`smallest`] and [`largest`].
1999/// Marker indicating that `Self` is a tuple where all members are of the type `T`.
2000/// Cannot be an associated type as we require the empty tuple to implement this trait
2001/// for all types `T`.
2002#[diagnostic::on_unimplemented(message = "`{Self}` is not a homogeneous tuple")]
2003#[unstable(feature = "cmp_splat_internals", issue = "160728")]
2004#[rustc_const_unstable(feature = "cmp_splat_internals", issue = "160728")]
2005const trait HomogeneousTuple<T>: crate::marker::Tuple {}
2006
2007/// Implements [`HomogeneousTuple`] for a provided tuple.
2008macro impl_homogeneous_tuple($($x:ident,)*) {
2009 #[unstable(feature = "cmp_splat_internals", issue = "160728")]
2010 #[rustc_const_unstable(feature = "cmp_splat_internals", issue = "160728")]
2011 const impl<T> HomogeneousTuple<T> for ($(${ignore($x)}T,)*) { }
2012}
2013
2014impl_tuples! {
2015 impl_homogeneous_tuple,
2016}
2017
2018/// Compares and returns the minimum of the provided values.
2019///
2020/// Returns the first argument if the comparison determines them to be equal.
2021///
2022/// Internally uses [`Ord::min`].
2023///
2024/// # Examples
2025///
2026/// ```
2027/// #![feature(cmp_splat)]
2028/// use std::cmp;
2029///
2030/// assert_eq!(cmp::smallest(1), 1);
2031/// assert_eq!(cmp::smallest(1, 2), 1);
2032/// assert_eq!(cmp::smallest(3, 2, 1), 1);
2033/// assert_eq!(cmp::smallest(1, 2, 3, 4), 1);
2034/// ```
2035/// ```
2036/// #![feature(cmp_splat)]
2037/// use std::cmp::{self, Ordering};
2038///
2039/// #[derive(Eq)]
2040/// struct Equal(&'static str);
2041///
2042/// impl PartialEq for Equal {
2043/// fn eq(&self, other: &Self) -> bool { true }
2044/// }
2045/// impl PartialOrd for Equal {
2046/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
2047/// }
2048/// impl Ord for Equal {
2049/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
2050/// }
2051///
2052/// assert_eq!(cmp::smallest(Equal("v1"), Equal("v2")).0, "v1");
2053/// ```
2054///
2055/// # Stability
2056///
2057/// This function is added in its current form as an experiment in variadic functions.
2058/// In a future iteration of the feature, this function may be removed in favour of
2059/// making [`min`] itself variadic instead.
2060#[inline]
2061#[must_use]
2062#[unstable(feature = "cmp_splat", issue = "160728")]
2063#[rustc_const_unstable(feature = "cmp_splat", issue = "160728")]
2064#[expect(private_bounds, reason = "`SmallestArgs` is an internal implementation detail")]
2065#[cfg(not(test))] // FIXME: splat interacts poorly with the double linking of `core` in tests
2066pub const fn smallest<T: [const] Ord + [const] Destruct>(
2067 v1: T,
2068 #[rustc_splat] args: impl [const] SmallestArgs<T>,
2069) -> T {
2070 SmallestArgs::smallest(v1, args)
2071}
2072
2073/// Implementation detail for [`smallest`].
2074#[diagnostic::on_unimplemented(message = "`{Self}` is not a valid set of arguments for `smallest`")]
2075#[unstable(feature = "cmp_splat_internals", issue = "160728")]
2076#[rustc_const_unstable(feature = "cmp_splat_internals", issue = "160728")]
2077const trait SmallestArgs<T>: HomogeneousTuple<T> {
2078 /// Reduces all elements of a homogeneous tuple to its smallest value.
2079 fn smallest(v1: T, args: Self) -> T;
2080}
2081
2082/// Implements [`SmallestArgs`] for a provided tuple if applicable.
2083macro impl_smallest_args($($x:ident,)*) {
2084 #[unstable(feature = "cmp_splat_internals", issue = "160728")]
2085 #[rustc_const_unstable(feature = "cmp_splat_internals", issue = "160728")]
2086 const impl<T> SmallestArgs<T> for ($(${ignore($x)}T,)*)
2087 where
2088 T: [const] Destruct + [const] Ord,
2089 {
2090 #[inline(always)] // improves unoptimised codegen
2091 fn smallest(v1: T, ($($x,)*): Self) -> T {
2092 v1$(.min($x))*
2093 }
2094 }
2095}
2096
2097impl_tuples! {
2098 impl_smallest_args,
2099}
2100
2101/// Compares and returns the maximum of the provided values.
2102///
2103/// Returns the last argument if the comparison determines them to be equal.
2104///
2105/// Internally uses [`Ord::max`].
2106///
2107/// # Examples
2108///
2109/// ```
2110/// #![feature(cmp_splat)]
2111/// use std::cmp;
2112///
2113/// assert_eq!(cmp::largest(1), 1);
2114/// assert_eq!(cmp::largest(1, 2), 2);
2115/// assert_eq!(cmp::largest(3, 2, 1), 3);
2116/// assert_eq!(cmp::largest(1, 2, 3, 4), 4);
2117/// ```
2118/// ```
2119/// #![feature(cmp_splat)]
2120/// use std::cmp::{self, Ordering};
2121///
2122/// #[derive(Eq)]
2123/// struct Equal(&'static str);
2124///
2125/// impl PartialEq for Equal {
2126/// fn eq(&self, other: &Self) -> bool { true }
2127/// }
2128/// impl PartialOrd for Equal {
2129/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
2130/// }
2131/// impl Ord for Equal {
2132/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
2133/// }
2134///
2135/// assert_eq!(cmp::largest(Equal("v1"), Equal("v2")).0, "v2");
2136/// ```
2137///
2138/// # Stability
2139///
2140/// This function is added in its current form as an experiment in variadic functions.
2141/// In a future iteration of the feature, this function may be removed in favour of
2142/// making [`max`] itself variadic instead.
2143#[inline]
2144#[must_use]
2145#[unstable(feature = "cmp_splat", issue = "160728")]
2146#[rustc_const_unstable(feature = "cmp_splat", issue = "160728")]
2147#[expect(private_bounds, reason = "`LargestArgs` is an internal implementation detail")]
2148#[cfg(not(test))] // FIXME: splat interacts poorly with the double linking of `core` in tests
2149pub const fn largest<T: [const] Ord + [const] Destruct>(
2150 v1: T,
2151 #[rustc_splat] args: impl [const] LargestArgs<T>,
2152) -> T {
2153 LargestArgs::largest(v1, args)
2154}
2155
2156/// Implementation detail for [`largest`].
2157#[diagnostic::on_unimplemented(message = "`{Self}` is not a valid set of arguments for `largest`")]
2158#[unstable(feature = "cmp_splat_internals", issue = "160728")]
2159#[rustc_const_unstable(feature = "cmp_splat_internals", issue = "160728")]
2160const trait LargestArgs<T>: HomogeneousTuple<T> {
2161 /// Reduces all elements of a homogeneous tuple to its largest value.
2162 fn largest(v1: T, args: Self) -> T;
2163}
2164
2165/// Implements [`LargestArgs`] for a provided tuple if applicable.
2166macro impl_largest_args($($x:ident,)*) {
2167 #[unstable(feature = "cmp_splat_internals", issue = "160728")]
2168 #[rustc_const_unstable(feature = "cmp_splat_internals", issue = "160728")]
2169 const impl<T> LargestArgs<T> for ($(${ignore($x)}T,)*)
2170 where
2171 T: [const] Destruct + [const] Ord,
2172 {
2173 #[inline(always)] // improves unoptimised codegen
2174 fn largest(v1: T, ($($x,)*): Self) -> T {
2175 v1$(.max($x))*
2176 }
2177 }
2178}
2179
2180impl_tuples! {
2181 impl_largest_args,
2182}
2183
2184// Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
2185mod impls {
2186 use crate::cmp::Ordering::{self, Equal, Greater, Less};
2187 use crate::hint::unreachable_unchecked;
2188 use crate::marker::PointeeSized;
2189 use crate::ops::ControlFlow::{self, Break, Continue};
2190 use crate::panic::const_assert;
2191
2192 /// Implements `PartialEq` for primitive types.
2193 ///
2194 /// Primitive types have a compiler-defined primitive implementation of `==` and `!=`.
2195 /// This implements the `PartialEq` trait in terms of those primitive implementations.
2196 ///
2197 /// NOTE: Calling this on a non-primitive type (such as `()`)
2198 /// leads to an infinitely-looping self-recursive implementation.
2199 macro_rules! impl_partial_eq_for_primitive {
2200 ($($t:ty)*) => ($(
2201 #[stable(feature = "rust1", since = "1.0.0")]
2202 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2203 const impl PartialEq for $t {
2204 #[inline]
2205 #[ferrocene::prevalidated]
2206 fn eq(&self, other: &Self) -> bool { *self == *other }
2207 // Override the default to use the primitive implementation for `!=`.
2208 #[inline]
2209 #[ferrocene::prevalidated]
2210 fn ne(&self, other: &Self) -> bool { *self != *other }
2211 }
2212 )*)
2213 }
2214
2215 impl_partial_eq_for_primitive! {
2216 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128
2217 }
2218
2219 #[stable(feature = "rust1", since = "1.0.0")]
2220 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2221 const impl PartialEq for () {
2222 #[inline]
2223 #[ferrocene::prevalidated]
2224 fn eq(&self, _other: &()) -> bool {
2225 true
2226 }
2227 #[inline]
2228 #[ferrocene::prevalidated]
2229 fn ne(&self, _other: &()) -> bool {
2230 false
2231 }
2232 }
2233
2234 macro_rules! eq_impl {
2235 ($($t:ty)*) => ($(
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2238 const impl Eq for $t {}
2239 )*)
2240 }
2241
2242 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
2243
2244 #[rustfmt::skip]
2245 macro_rules! partial_ord_methods_primitive_impl {
2246 () => {
2247 #[inline(always)]
2248 #[ferrocene::prevalidated]
2249 fn lt(&self, other: &Self) -> bool { *self < *other }
2250 #[inline(always)]
2251 #[ferrocene::prevalidated]
2252 fn le(&self, other: &Self) -> bool { *self <= *other }
2253 #[inline(always)]
2254 #[ferrocene::prevalidated]
2255 fn gt(&self, other: &Self) -> bool { *self > *other }
2256 #[inline(always)]
2257 #[ferrocene::prevalidated]
2258 fn ge(&self, other: &Self) -> bool { *self >= *other }
2259
2260 // These implementations are the same for `Ord` or `PartialOrd` types
2261 // because if either is NAN the `==` test will fail so we end up in
2262 // the `Break` case and the comparison will correctly return `false`.
2263
2264 #[inline]
2265 #[ferrocene::prevalidated]
2266 fn __chaining_lt(&self, other: &Self) -> ControlFlow<bool> {
2267 let (lhs, rhs) = (*self, *other);
2268 if lhs == rhs { Continue(()) } else { Break(lhs < rhs) }
2269 }
2270 #[inline]
2271 #[ferrocene::prevalidated]
2272 fn __chaining_le(&self, other: &Self) -> ControlFlow<bool> {
2273 let (lhs, rhs) = (*self, *other);
2274 if lhs == rhs { Continue(()) } else { Break(lhs <= rhs) }
2275 }
2276 #[inline]
2277 #[ferrocene::prevalidated]
2278 fn __chaining_gt(&self, other: &Self) -> ControlFlow<bool> {
2279 let (lhs, rhs) = (*self, *other);
2280 if lhs == rhs { Continue(()) } else { Break(lhs > rhs) }
2281 }
2282 #[inline]
2283 #[ferrocene::prevalidated]
2284 fn __chaining_ge(&self, other: &Self) -> ControlFlow<bool> {
2285 let (lhs, rhs) = (*self, *other);
2286 if lhs == rhs { Continue(()) } else { Break(lhs >= rhs) }
2287 }
2288 };
2289 }
2290
2291 macro_rules! partial_ord_impl {
2292 ($($t:ty)*) => ($(
2293 #[stable(feature = "rust1", since = "1.0.0")]
2294 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2295 const impl PartialOrd for $t {
2296 #[inline]
2297 #[ferrocene::prevalidated]
2298 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2299 match (*self <= *other, *self >= *other) {
2300 (false, false) => None,
2301 (false, true) => Some(Greater),
2302 (true, false) => Some(Less),
2303 (true, true) => Some(Equal),
2304 }
2305 }
2306
2307 partial_ord_methods_primitive_impl!();
2308 }
2309 )*)
2310 }
2311
2312 #[stable(feature = "rust1", since = "1.0.0")]
2313 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2314 const impl PartialOrd for () {
2315 #[inline]
2316 #[ferrocene::prevalidated]
2317 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
2318 Some(Equal)
2319 }
2320 }
2321
2322 #[stable(feature = "rust1", since = "1.0.0")]
2323 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2324 const impl PartialOrd for bool {
2325 #[inline]
2326 #[ferrocene::prevalidated]
2327 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
2328 Some(self.cmp(other))
2329 }
2330
2331 partial_ord_methods_primitive_impl!();
2332 }
2333
2334 partial_ord_impl! { f16 f32 f64 f128 }
2335
2336 macro_rules! min_max_impl {
2337 (char) => {
2338 #[inline]
2339 fn min(self, other: Self) -> Self {
2340 let c = u32::min(self as u32, other as u32);
2341 // SAFETY: it's one of the inputs
2342 unsafe { char::from_u32_unchecked(c) }
2343 }
2344
2345 #[inline]
2346 fn max(self, other: Self) -> Self {
2347 let c = u32::max(self as u32, other as u32);
2348 // SAFETY: it's one of the inputs
2349 unsafe { char::from_u32_unchecked(c) }
2350 }
2351 };
2352 ($t:ident) => {
2353 #[ferrocene::prevalidated]
2354 #[inline]
2355 fn min(self, other: Self) -> Self {
2356 crate::intrinsics::integer_min(self, other)
2357 }
2358
2359 #[ferrocene::prevalidated]
2360 #[inline]
2361 fn max(self, other: Self) -> Self {
2362 crate::intrinsics::integer_max(self, other)
2363 }
2364 };
2365 }
2366
2367 macro_rules! ord_impl {
2368 ($($t:ident)*) => ($(
2369 #[stable(feature = "rust1", since = "1.0.0")]
2370 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2371 const impl PartialOrd for $t {
2372 #[inline]
2373 #[ferrocene::prevalidated]
2374 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2375 Some(crate::intrinsics::three_way_compare(*self, *other))
2376 }
2377
2378 partial_ord_methods_primitive_impl!();
2379 }
2380
2381 #[stable(feature = "rust1", since = "1.0.0")]
2382 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2383 const impl Ord for $t {
2384 #[inline]
2385 #[ferrocene::prevalidated]
2386 fn cmp(&self, other: &Self) -> Ordering {
2387 crate::intrinsics::three_way_compare(*self, *other)
2388 }
2389
2390 #[inline]
2391 #[track_caller]
2392 fn clamp(self, min: Self, max: Self) -> Self
2393 {
2394 const_assert!(
2395 min <= max,
2396 "min > max",
2397 "min > max. min = {min:?}, max = {max:?}",
2398 min: $t,
2399 max: $t,
2400 );
2401 if self < min {
2402 min
2403 } else if self > max {
2404 max
2405 } else {
2406 self
2407 }
2408 }
2409
2410 min_max_impl!($t);
2411 }
2412 )*)
2413 }
2414
2415 #[stable(feature = "rust1", since = "1.0.0")]
2416 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2417 const impl Ord for () {
2418 #[inline]
2419 #[ferrocene::prevalidated]
2420 fn cmp(&self, _other: &()) -> Ordering {
2421 Equal
2422 }
2423 }
2424
2425 #[stable(feature = "rust1", since = "1.0.0")]
2426 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2427 const impl Ord for bool {
2428 #[inline]
2429 #[ferrocene::prevalidated]
2430 fn cmp(&self, other: &bool) -> Ordering {
2431 // Casting to i8's and converting the difference to an Ordering generates
2432 // more optimal assembly.
2433 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
2434 match (*self as i8) - (*other as i8) {
2435 -1 => Less,
2436 0 => Equal,
2437 1 => Greater,
2438 #[ferrocene::annotation(
2439 "This match arm cannot be covered because it is unreachable. See the safety comment below."
2440 )]
2441 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
2442 _ => unsafe { unreachable_unchecked() },
2443 }
2444 }
2445
2446 #[inline]
2447 #[ferrocene::prevalidated]
2448 fn min(self, other: bool) -> bool {
2449 self & other
2450 }
2451
2452 #[inline]
2453 #[ferrocene::prevalidated]
2454 fn max(self, other: bool) -> bool {
2455 self | other
2456 }
2457
2458 #[inline]
2459 #[ferrocene::prevalidated]
2460 fn clamp(self, min: bool, max: bool) -> bool {
2461 assert!(min <= max);
2462 self.max(min).min(max)
2463 }
2464 }
2465
2466 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
2467
2468 #[stable(feature = "never_type", since = "CURRENT_RUSTC_VERSION")]
2469 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2470 const impl PartialEq for ! {
2471 #[inline]
2472 #[ferrocene::prevalidated]
2473 fn eq(&self, _: &!) -> bool {
2474 *self
2475 }
2476 }
2477
2478 #[stable(feature = "never_type", since = "CURRENT_RUSTC_VERSION")]
2479 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2480 const impl Eq for ! {}
2481
2482 #[stable(feature = "never_type", since = "CURRENT_RUSTC_VERSION")]
2483 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2484 const impl PartialOrd for ! {
2485 #[inline]
2486 #[ferrocene::prevalidated]
2487 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
2488 *self
2489 }
2490 }
2491
2492 #[stable(feature = "never_type", since = "CURRENT_RUSTC_VERSION")]
2493 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2494 const impl Ord for ! {
2495 #[inline]
2496 #[ferrocene::prevalidated]
2497 fn cmp(&self, _: &!) -> Ordering {
2498 *self
2499 }
2500 }
2501
2502 // & pointers
2503
2504 #[stable(feature = "rust1", since = "1.0.0")]
2505 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2506 const impl<A: PointeeSized, B: PointeeSized> PartialEq<&B> for &A
2507 where
2508 A: [const] PartialEq<B>,
2509 {
2510 #[inline]
2511 #[ferrocene::prevalidated]
2512 fn eq(&self, other: &&B) -> bool {
2513 PartialEq::eq(*self, *other)
2514 }
2515 #[inline]
2516 #[ferrocene::prevalidated]
2517 fn ne(&self, other: &&B) -> bool {
2518 PartialEq::ne(*self, *other)
2519 }
2520 }
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2523 const impl<A: PointeeSized, B: PointeeSized> PartialOrd<&B> for &A
2524 where
2525 A: [const] PartialOrd<B>,
2526 {
2527 #[inline]
2528 #[ferrocene::prevalidated]
2529 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
2530 PartialOrd::partial_cmp(*self, *other)
2531 }
2532 #[inline]
2533 #[ferrocene::prevalidated]
2534 fn lt(&self, other: &&B) -> bool {
2535 PartialOrd::lt(*self, *other)
2536 }
2537 #[inline]
2538 #[ferrocene::prevalidated]
2539 fn le(&self, other: &&B) -> bool {
2540 PartialOrd::le(*self, *other)
2541 }
2542 #[inline]
2543 #[ferrocene::prevalidated]
2544 fn gt(&self, other: &&B) -> bool {
2545 PartialOrd::gt(*self, *other)
2546 }
2547 #[inline]
2548 #[ferrocene::prevalidated]
2549 fn ge(&self, other: &&B) -> bool {
2550 PartialOrd::ge(*self, *other)
2551 }
2552 #[inline]
2553 #[ferrocene::prevalidated]
2554 fn __chaining_lt(&self, other: &&B) -> ControlFlow<bool> {
2555 PartialOrd::__chaining_lt(*self, *other)
2556 }
2557 #[inline]
2558 #[ferrocene::prevalidated]
2559 fn __chaining_le(&self, other: &&B) -> ControlFlow<bool> {
2560 PartialOrd::__chaining_le(*self, *other)
2561 }
2562 #[inline]
2563 #[ferrocene::prevalidated]
2564 fn __chaining_gt(&self, other: &&B) -> ControlFlow<bool> {
2565 PartialOrd::__chaining_gt(*self, *other)
2566 }
2567 #[inline]
2568 #[ferrocene::prevalidated]
2569 fn __chaining_ge(&self, other: &&B) -> ControlFlow<bool> {
2570 PartialOrd::__chaining_ge(*self, *other)
2571 }
2572 }
2573 #[stable(feature = "rust1", since = "1.0.0")]
2574 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2575 const impl<A: PointeeSized> Ord for &A
2576 where
2577 A: [const] Ord,
2578 {
2579 #[inline]
2580 #[ferrocene::prevalidated]
2581 fn cmp(&self, other: &Self) -> Ordering {
2582 Ord::cmp(*self, *other)
2583 }
2584 }
2585 #[stable(feature = "rust1", since = "1.0.0")]
2586 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2587 const impl<A: PointeeSized> Eq for &A where A: [const] Eq {}
2588
2589 // &mut pointers
2590
2591 #[stable(feature = "rust1", since = "1.0.0")]
2592 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2593 const impl<A: PointeeSized, B: PointeeSized> PartialEq<&mut B> for &mut A
2594 where
2595 A: [const] PartialEq<B>,
2596 {
2597 #[inline]
2598 #[ferrocene::prevalidated]
2599 fn eq(&self, other: &&mut B) -> bool {
2600 PartialEq::eq(*self, *other)
2601 }
2602 #[inline]
2603 #[ferrocene::prevalidated]
2604 fn ne(&self, other: &&mut B) -> bool {
2605 PartialEq::ne(*self, *other)
2606 }
2607 }
2608 #[stable(feature = "rust1", since = "1.0.0")]
2609 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2610 const impl<A: PointeeSized, B: PointeeSized> PartialOrd<&mut B> for &mut A
2611 where
2612 A: [const] PartialOrd<B>,
2613 {
2614 #[inline]
2615 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
2616 PartialOrd::partial_cmp(*self, *other)
2617 }
2618 #[inline]
2619 fn lt(&self, other: &&mut B) -> bool {
2620 PartialOrd::lt(*self, *other)
2621 }
2622 #[inline]
2623 fn le(&self, other: &&mut B) -> bool {
2624 PartialOrd::le(*self, *other)
2625 }
2626 #[inline]
2627 fn gt(&self, other: &&mut B) -> bool {
2628 PartialOrd::gt(*self, *other)
2629 }
2630 #[inline]
2631 fn ge(&self, other: &&mut B) -> bool {
2632 PartialOrd::ge(*self, *other)
2633 }
2634 #[inline]
2635 fn __chaining_lt(&self, other: &&mut B) -> ControlFlow<bool> {
2636 PartialOrd::__chaining_lt(*self, *other)
2637 }
2638 #[inline]
2639 fn __chaining_le(&self, other: &&mut B) -> ControlFlow<bool> {
2640 PartialOrd::__chaining_le(*self, *other)
2641 }
2642 #[inline]
2643 fn __chaining_gt(&self, other: &&mut B) -> ControlFlow<bool> {
2644 PartialOrd::__chaining_gt(*self, *other)
2645 }
2646 #[inline]
2647 fn __chaining_ge(&self, other: &&mut B) -> ControlFlow<bool> {
2648 PartialOrd::__chaining_ge(*self, *other)
2649 }
2650 }
2651 #[stable(feature = "rust1", since = "1.0.0")]
2652 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2653 const impl<A: PointeeSized> Ord for &mut A
2654 where
2655 A: [const] Ord,
2656 {
2657 #[inline]
2658 fn cmp(&self, other: &Self) -> Ordering {
2659 Ord::cmp(*self, *other)
2660 }
2661 }
2662 #[stable(feature = "rust1", since = "1.0.0")]
2663 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2664 const impl<A: PointeeSized> Eq for &mut A where A: [const] Eq {}
2665
2666 #[stable(feature = "rust1", since = "1.0.0")]
2667 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2668 const impl<A: PointeeSized, B: PointeeSized> PartialEq<&mut B> for &A
2669 where
2670 A: [const] PartialEq<B>,
2671 {
2672 #[inline]
2673 #[ferrocene::prevalidated]
2674 fn eq(&self, other: &&mut B) -> bool {
2675 PartialEq::eq(*self, *other)
2676 }
2677 #[inline]
2678 #[ferrocene::prevalidated]
2679 fn ne(&self, other: &&mut B) -> bool {
2680 PartialEq::ne(*self, *other)
2681 }
2682 }
2683
2684 #[stable(feature = "rust1", since = "1.0.0")]
2685 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2686 const impl<A: PointeeSized, B: PointeeSized> PartialEq<&B> for &mut A
2687 where
2688 A: [const] PartialEq<B>,
2689 {
2690 #[inline]
2691 #[ferrocene::prevalidated]
2692 fn eq(&self, other: &&B) -> bool {
2693 PartialEq::eq(*self, *other)
2694 }
2695 #[inline]
2696 #[ferrocene::prevalidated]
2697 fn ne(&self, other: &&B) -> bool {
2698 PartialEq::ne(*self, *other)
2699 }
2700 }
2701}