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