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