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>:
1355 [const] PartialEq<Rhs> + PointeeSized
1356{
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
1496#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1497const fn default_chaining_impl<T, U>(
1498 lhs: &T,
1499 rhs: &U,
1500 p: impl [const] FnOnce(Ordering) -> bool + [const] Destruct,
1501) -> ControlFlow<bool>
1502where
1503 T: [const] PartialOrd<U> + PointeeSized,
1504 U: PointeeSized,
1505{
1506 // It's important that this only call `partial_cmp` once, not call `eq` then
1507 // one of the relational operators. We don't want to `bcmp`-then-`memcp` a
1508 // `String`, for example, or similarly for other data structures (#108157).
1509 match <T as PartialOrd<U>>::partial_cmp(lhs, rhs) {
1510 Some(Equal) => ControlFlow::Continue(()),
1511 Some(c) => ControlFlow::Break(p(c)),
1512 None => ControlFlow::Break(false),
1513 }
1514}
1515
1516/// Derive macro generating an impl of the trait [`PartialOrd`].
1517/// The behavior of this macro is described in detail [here](PartialOrd#derivable).
1518#[rustc_builtin_macro]
1519#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1520#[allow_internal_unstable(core_intrinsics)]
1521pub macro PartialOrd($item:item) {
1522 /* compiler built-in */
1523}
1524
1525/// Compares and returns the minimum of two values.
1526///
1527/// Returns the first argument if the comparison determines them to be equal.
1528///
1529/// Internally uses an alias to [`Ord::min`].
1530///
1531/// # Examples
1532///
1533/// ```
1534/// use std::cmp;
1535///
1536/// assert_eq!(cmp::min(1, 2), 1);
1537/// assert_eq!(cmp::min(2, 2), 2);
1538/// ```
1539/// ```
1540/// use std::cmp::{self, Ordering};
1541///
1542/// #[derive(Eq)]
1543/// struct Equal(&'static str);
1544///
1545/// impl PartialEq for Equal {
1546/// fn eq(&self, other: &Self) -> bool { true }
1547/// }
1548/// impl PartialOrd for Equal {
1549/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1550/// }
1551/// impl Ord for Equal {
1552/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1553/// }
1554///
1555/// assert_eq!(cmp::min(Equal("v1"), Equal("v2")).0, "v1");
1556/// ```
1557#[inline]
1558#[must_use]
1559#[stable(feature = "rust1", since = "1.0.0")]
1560#[rustc_diagnostic_item = "cmp_min"]
1561#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1562pub const fn min<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1563 v1.min(v2)
1564}
1565
1566/// Returns the minimum of two values with respect to the specified comparison function.
1567///
1568/// Returns the first argument if the comparison determines them to be equal.
1569///
1570/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1571/// always passed as the first argument and `v2` as the second.
1572///
1573/// # Examples
1574///
1575/// ```
1576/// use std::cmp;
1577///
1578/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1579///
1580/// let result = cmp::min_by(2, -1, abs_cmp);
1581/// assert_eq!(result, -1);
1582///
1583/// let result = cmp::min_by(2, -3, abs_cmp);
1584/// assert_eq!(result, 2);
1585///
1586/// let result = cmp::min_by(1, -1, abs_cmp);
1587/// assert_eq!(result, 1);
1588/// ```
1589#[inline]
1590#[must_use]
1591#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1592#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1593pub const fn min_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1594 v1: T,
1595 v2: T,
1596 compare: F,
1597) -> T {
1598 if compare(&v1, &v2).is_le() { v1 } else { v2 }
1599}
1600
1601/// Returns the element that gives the minimum value from the specified function.
1602///
1603/// Returns the first argument if the comparison determines them to be equal.
1604///
1605/// # Examples
1606///
1607/// ```
1608/// use std::cmp;
1609///
1610/// let result = cmp::min_by_key(2, -1, |x: &i32| x.abs());
1611/// assert_eq!(result, -1);
1612///
1613/// let result = cmp::min_by_key(2, -3, |x: &i32| x.abs());
1614/// assert_eq!(result, 2);
1615///
1616/// let result = cmp::min_by_key(1, -1, |x: &i32| x.abs());
1617/// assert_eq!(result, 1);
1618/// ```
1619#[inline]
1620#[must_use]
1621#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1622#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1623pub const fn min_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1624where
1625 T: [const] Destruct,
1626 F: [const] FnMut(&T) -> K + [const] Destruct,
1627 K: [const] Ord + [const] Destruct,
1628{
1629 if f(&v2) < f(&v1) { v2 } else { v1 }
1630}
1631
1632/// Compares and returns the maximum of two values.
1633///
1634/// Returns the second argument if the comparison determines them to be equal.
1635///
1636/// Internally uses an alias to [`Ord::max`].
1637///
1638/// # Examples
1639///
1640/// ```
1641/// use std::cmp;
1642///
1643/// assert_eq!(cmp::max(1, 2), 2);
1644/// assert_eq!(cmp::max(2, 2), 2);
1645/// ```
1646/// ```
1647/// use std::cmp::{self, Ordering};
1648///
1649/// #[derive(Eq)]
1650/// struct Equal(&'static str);
1651///
1652/// impl PartialEq for Equal {
1653/// fn eq(&self, other: &Self) -> bool { true }
1654/// }
1655/// impl PartialOrd for Equal {
1656/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1657/// }
1658/// impl Ord for Equal {
1659/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1660/// }
1661///
1662/// assert_eq!(cmp::max(Equal("v1"), Equal("v2")).0, "v2");
1663/// ```
1664#[inline]
1665#[must_use]
1666#[stable(feature = "rust1", since = "1.0.0")]
1667#[rustc_diagnostic_item = "cmp_max"]
1668#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1669pub const fn max<T: [const] Ord + [const] Destruct>(v1: T, v2: T) -> T {
1670 v1.max(v2)
1671}
1672
1673/// Returns the maximum of two values with respect to the specified comparison function.
1674///
1675/// Returns the second argument if the comparison determines them to be equal.
1676///
1677/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1678/// always passed as the first argument and `v2` as the second.
1679///
1680/// # Examples
1681///
1682/// ```
1683/// use std::cmp;
1684///
1685/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1686///
1687/// let result = cmp::max_by(3, -2, abs_cmp) ;
1688/// assert_eq!(result, 3);
1689///
1690/// let result = cmp::max_by(1, -2, abs_cmp);
1691/// assert_eq!(result, -2);
1692///
1693/// let result = cmp::max_by(1, -1, abs_cmp);
1694/// assert_eq!(result, -1);
1695/// ```
1696#[inline]
1697#[must_use]
1698#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1699#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1700pub const fn max_by<T: [const] Destruct, F: [const] FnOnce(&T, &T) -> Ordering>(
1701 v1: T,
1702 v2: T,
1703 compare: F,
1704) -> T {
1705 if compare(&v1, &v2).is_gt() { v1 } else { v2 }
1706}
1707
1708/// Returns the element that gives the maximum value from the specified function.
1709///
1710/// Returns the second argument if the comparison determines them to be equal.
1711///
1712/// # Examples
1713///
1714/// ```
1715/// use std::cmp;
1716///
1717/// let result = cmp::max_by_key(3, -2, |x: &i32| x.abs());
1718/// assert_eq!(result, 3);
1719///
1720/// let result = cmp::max_by_key(1, -2, |x: &i32| x.abs());
1721/// assert_eq!(result, -2);
1722///
1723/// let result = cmp::max_by_key(1, -1, |x: &i32| x.abs());
1724/// assert_eq!(result, -1);
1725/// ```
1726#[inline]
1727#[must_use]
1728#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1729#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1730pub const fn max_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> T
1731where
1732 T: [const] Destruct,
1733 F: [const] FnMut(&T) -> K + [const] Destruct,
1734 K: [const] Ord + [const] Destruct,
1735{
1736 if f(&v2) < f(&v1) { v1 } else { v2 }
1737}
1738
1739/// Compares and sorts two values, returning minimum and maximum.
1740///
1741/// Returns `[v1, v2]` if the comparison determines them to be equal.
1742///
1743/// # Examples
1744///
1745/// ```
1746/// #![feature(cmp_minmax)]
1747/// use std::cmp;
1748///
1749/// assert_eq!(cmp::minmax(1, 2), [1, 2]);
1750/// assert_eq!(cmp::minmax(2, 1), [1, 2]);
1751///
1752/// // You can destructure the result using array patterns
1753/// let [min, max] = cmp::minmax(42, 17);
1754/// assert_eq!(min, 17);
1755/// assert_eq!(max, 42);
1756/// ```
1757/// ```
1758/// #![feature(cmp_minmax)]
1759/// use std::cmp::{self, Ordering};
1760///
1761/// #[derive(Eq)]
1762/// struct Equal(&'static str);
1763///
1764/// impl PartialEq for Equal {
1765/// fn eq(&self, other: &Self) -> bool { true }
1766/// }
1767/// impl PartialOrd for Equal {
1768/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(Ordering::Equal) }
1769/// }
1770/// impl Ord for Equal {
1771/// fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal }
1772/// }
1773///
1774/// assert_eq!(cmp::minmax(Equal("v1"), Equal("v2")).map(|v| v.0), ["v1", "v2"]);
1775/// ```
1776#[inline]
1777#[must_use]
1778#[unstable(feature = "cmp_minmax", issue = "115939")]
1779#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1780pub const fn minmax<T>(v1: T, v2: T) -> [T; 2]
1781where
1782 T: [const] Ord,
1783{
1784 if v2 < v1 { [v2, v1] } else { [v1, v2] }
1785}
1786
1787/// Returns minimum and maximum values with respect to the specified comparison function.
1788///
1789/// Returns `[v1, v2]` if the comparison determines them to be equal.
1790///
1791/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is
1792/// always passed as the first argument and `v2` as the second.
1793///
1794/// # Examples
1795///
1796/// ```
1797/// #![feature(cmp_minmax)]
1798/// use std::cmp;
1799///
1800/// let abs_cmp = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
1801///
1802/// assert_eq!(cmp::minmax_by(-2, 1, abs_cmp), [1, -2]);
1803/// assert_eq!(cmp::minmax_by(-1, 2, abs_cmp), [-1, 2]);
1804/// assert_eq!(cmp::minmax_by(-2, 2, abs_cmp), [-2, 2]);
1805///
1806/// // You can destructure the result using array patterns
1807/// let [min, max] = cmp::minmax_by(-42, 17, abs_cmp);
1808/// assert_eq!(min, 17);
1809/// assert_eq!(max, -42);
1810/// ```
1811#[inline]
1812#[must_use]
1813#[unstable(feature = "cmp_minmax", issue = "115939")]
1814#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1815pub const fn minmax_by<T, F>(v1: T, v2: T, compare: F) -> [T; 2]
1816where
1817 F: [const] FnOnce(&T, &T) -> Ordering,
1818{
1819 if compare(&v1, &v2).is_le() { [v1, v2] } else { [v2, v1] }
1820}
1821
1822/// Returns minimum and maximum values with respect to the specified key function.
1823///
1824/// Returns `[v1, v2]` if the comparison determines them to be equal.
1825///
1826/// # Examples
1827///
1828/// ```
1829/// #![feature(cmp_minmax)]
1830/// use std::cmp;
1831///
1832/// assert_eq!(cmp::minmax_by_key(-2, 1, |x: &i32| x.abs()), [1, -2]);
1833/// assert_eq!(cmp::minmax_by_key(-2, 2, |x: &i32| x.abs()), [-2, 2]);
1834///
1835/// // You can destructure the result using array patterns
1836/// let [min, max] = cmp::minmax_by_key(-42, 17, |x: &i32| x.abs());
1837/// assert_eq!(min, 17);
1838/// assert_eq!(max, -42);
1839/// ```
1840#[inline]
1841#[must_use]
1842#[unstable(feature = "cmp_minmax", issue = "115939")]
1843#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1844pub const fn minmax_by_key<T, F, K>(v1: T, v2: T, mut f: F) -> [T; 2]
1845where
1846 F: [const] FnMut(&T) -> K + [const] Destruct,
1847 K: [const] Ord + [const] Destruct,
1848{
1849 if f(&v2) < f(&v1) { [v2, v1] } else { [v1, v2] }
1850}
1851
1852// Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1853mod impls {
1854 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1855 use crate::hint::unreachable_unchecked;
1856 use crate::marker::PointeeSized;
1857 use crate::ops::ControlFlow::{self, Break, Continue};
1858
1859 macro_rules! partial_eq_impl {
1860 ($($t:ty)*) => ($(
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1863 impl const PartialEq for $t {
1864 #[inline]
1865 fn eq(&self, other: &Self) -> bool { *self == *other }
1866 #[inline]
1867 fn ne(&self, other: &Self) -> bool { *self != *other }
1868 }
1869 )*)
1870 }
1871
1872 #[stable(feature = "rust1", since = "1.0.0")]
1873 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1874 impl const PartialEq for () {
1875 #[inline]
1876 fn eq(&self, _other: &()) -> bool {
1877 true
1878 }
1879 #[inline]
1880 fn ne(&self, _other: &()) -> bool {
1881 false
1882 }
1883 }
1884
1885 partial_eq_impl! {
1886 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128
1887 }
1888
1889 macro_rules! eq_impl {
1890 ($($t:ty)*) => ($(
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1893 impl const Eq for $t {}
1894 )*)
1895 }
1896
1897 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1898
1899 #[rustfmt::skip]
1900 macro_rules! partial_ord_methods_primitive_impl {
1901 () => {
1902 #[inline(always)]
1903 fn lt(&self, other: &Self) -> bool { *self < *other }
1904 #[inline(always)]
1905 fn le(&self, other: &Self) -> bool { *self <= *other }
1906 #[inline(always)]
1907 fn gt(&self, other: &Self) -> bool { *self > *other }
1908 #[inline(always)]
1909 fn ge(&self, other: &Self) -> bool { *self >= *other }
1910
1911 // These implementations are the same for `Ord` or `PartialOrd` types
1912 // because if either is NAN the `==` test will fail so we end up in
1913 // the `Break` case and the comparison will correctly return `false`.
1914
1915 #[inline]
1916 fn __chaining_lt(&self, other: &Self) -> ControlFlow<bool> {
1917 let (lhs, rhs) = (*self, *other);
1918 if lhs == rhs { Continue(()) } else { Break(lhs < rhs) }
1919 }
1920 #[inline]
1921 fn __chaining_le(&self, other: &Self) -> ControlFlow<bool> {
1922 let (lhs, rhs) = (*self, *other);
1923 if lhs == rhs { Continue(()) } else { Break(lhs <= rhs) }
1924 }
1925 #[inline]
1926 fn __chaining_gt(&self, other: &Self) -> ControlFlow<bool> {
1927 let (lhs, rhs) = (*self, *other);
1928 if lhs == rhs { Continue(()) } else { Break(lhs > rhs) }
1929 }
1930 #[inline]
1931 fn __chaining_ge(&self, other: &Self) -> ControlFlow<bool> {
1932 let (lhs, rhs) = (*self, *other);
1933 if lhs == rhs { Continue(()) } else { Break(lhs >= rhs) }
1934 }
1935 };
1936 }
1937
1938 macro_rules! partial_ord_impl {
1939 ($($t:ty)*) => ($(
1940 #[stable(feature = "rust1", since = "1.0.0")]
1941 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1942 impl const PartialOrd for $t {
1943 #[inline]
1944 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1945 match (*self <= *other, *self >= *other) {
1946 (false, false) => None,
1947 (false, true) => Some(Greater),
1948 (true, false) => Some(Less),
1949 (true, true) => Some(Equal),
1950 }
1951 }
1952
1953 partial_ord_methods_primitive_impl!();
1954 }
1955 )*)
1956 }
1957
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1960 impl const PartialOrd for () {
1961 #[inline]
1962 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1963 Some(Equal)
1964 }
1965 }
1966
1967 #[stable(feature = "rust1", since = "1.0.0")]
1968 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1969 impl const PartialOrd for bool {
1970 #[inline]
1971 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1972 Some(self.cmp(other))
1973 }
1974
1975 partial_ord_methods_primitive_impl!();
1976 }
1977
1978 partial_ord_impl! { f16 f32 f64 f128 }
1979
1980 macro_rules! ord_impl {
1981 ($($t:ty)*) => ($(
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1984 impl const PartialOrd for $t {
1985 #[inline]
1986 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1987 Some(crate::intrinsics::three_way_compare(*self, *other))
1988 }
1989
1990 partial_ord_methods_primitive_impl!();
1991 }
1992
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1995 impl const Ord for $t {
1996 #[inline]
1997 fn cmp(&self, other: &Self) -> Ordering {
1998 crate::intrinsics::three_way_compare(*self, *other)
1999 }
2000 }
2001 )*)
2002 }
2003
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2006 impl const Ord for () {
2007 #[inline]
2008 fn cmp(&self, _other: &()) -> Ordering {
2009 Equal
2010 }
2011 }
2012
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2015 impl const Ord for bool {
2016 #[inline]
2017 fn cmp(&self, other: &bool) -> Ordering {
2018 // Casting to i8's and converting the difference to an Ordering generates
2019 // more optimal assembly.
2020 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
2021 match (*self as i8) - (*other as i8) {
2022 -1 => Less,
2023 0 => Equal,
2024 1 => Greater,
2025 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
2026 _ => unsafe { unreachable_unchecked() },
2027 }
2028 }
2029
2030 #[inline]
2031 fn min(self, other: bool) -> bool {
2032 self & other
2033 }
2034
2035 #[inline]
2036 fn max(self, other: bool) -> bool {
2037 self | other
2038 }
2039
2040 #[inline]
2041 fn clamp(self, min: bool, max: bool) -> bool {
2042 assert!(min <= max);
2043 self.max(min).min(max)
2044 }
2045 }
2046
2047 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
2048
2049 #[unstable(feature = "never_type", issue = "35121")]
2050 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2051 impl const PartialEq for ! {
2052 #[inline]
2053 fn eq(&self, _: &!) -> bool {
2054 *self
2055 }
2056 }
2057
2058 #[unstable(feature = "never_type", issue = "35121")]
2059 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2060 impl const Eq for ! {}
2061
2062 #[unstable(feature = "never_type", issue = "35121")]
2063 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2064 impl const PartialOrd for ! {
2065 #[inline]
2066 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
2067 *self
2068 }
2069 }
2070
2071 #[unstable(feature = "never_type", issue = "35121")]
2072 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2073 impl const Ord for ! {
2074 #[inline]
2075 fn cmp(&self, _: &!) -> Ordering {
2076 *self
2077 }
2078 }
2079
2080 // & pointers
2081
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2084 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &A
2085 where
2086 A: [const] PartialEq<B>,
2087 {
2088 #[inline]
2089 fn eq(&self, other: &&B) -> bool {
2090 PartialEq::eq(*self, *other)
2091 }
2092 #[inline]
2093 fn ne(&self, other: &&B) -> bool {
2094 PartialEq::ne(*self, *other)
2095 }
2096 }
2097 #[stable(feature = "rust1", since = "1.0.0")]
2098 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2099 impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&B> for &A
2100 where
2101 A: [const] PartialOrd<B>,
2102 {
2103 #[inline]
2104 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
2105 PartialOrd::partial_cmp(*self, *other)
2106 }
2107 #[inline]
2108 fn lt(&self, other: &&B) -> bool {
2109 PartialOrd::lt(*self, *other)
2110 }
2111 #[inline]
2112 fn le(&self, other: &&B) -> bool {
2113 PartialOrd::le(*self, *other)
2114 }
2115 #[inline]
2116 fn gt(&self, other: &&B) -> bool {
2117 PartialOrd::gt(*self, *other)
2118 }
2119 #[inline]
2120 fn ge(&self, other: &&B) -> bool {
2121 PartialOrd::ge(*self, *other)
2122 }
2123 #[inline]
2124 fn __chaining_lt(&self, other: &&B) -> ControlFlow<bool> {
2125 PartialOrd::__chaining_lt(*self, *other)
2126 }
2127 #[inline]
2128 fn __chaining_le(&self, other: &&B) -> ControlFlow<bool> {
2129 PartialOrd::__chaining_le(*self, *other)
2130 }
2131 #[inline]
2132 fn __chaining_gt(&self, other: &&B) -> ControlFlow<bool> {
2133 PartialOrd::__chaining_gt(*self, *other)
2134 }
2135 #[inline]
2136 fn __chaining_ge(&self, other: &&B) -> ControlFlow<bool> {
2137 PartialOrd::__chaining_ge(*self, *other)
2138 }
2139 }
2140 #[stable(feature = "rust1", since = "1.0.0")]
2141 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2142 impl<A: PointeeSized> const Ord for &A
2143 where
2144 A: [const] Ord,
2145 {
2146 #[inline]
2147 fn cmp(&self, other: &Self) -> Ordering {
2148 Ord::cmp(*self, *other)
2149 }
2150 }
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2153 impl<A: PointeeSized> const Eq for &A where A: [const] Eq {}
2154
2155 // &mut pointers
2156
2157 #[stable(feature = "rust1", since = "1.0.0")]
2158 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2159 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &mut A
2160 where
2161 A: [const] PartialEq<B>,
2162 {
2163 #[inline]
2164 fn eq(&self, other: &&mut B) -> bool {
2165 PartialEq::eq(*self, *other)
2166 }
2167 #[inline]
2168 fn ne(&self, other: &&mut B) -> bool {
2169 PartialEq::ne(*self, *other)
2170 }
2171 }
2172 #[stable(feature = "rust1", since = "1.0.0")]
2173 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2174 impl<A: PointeeSized, B: PointeeSized> const PartialOrd<&mut B> for &mut A
2175 where
2176 A: [const] PartialOrd<B>,
2177 {
2178 #[inline]
2179 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
2180 PartialOrd::partial_cmp(*self, *other)
2181 }
2182 #[inline]
2183 fn lt(&self, other: &&mut B) -> bool {
2184 PartialOrd::lt(*self, *other)
2185 }
2186 #[inline]
2187 fn le(&self, other: &&mut B) -> bool {
2188 PartialOrd::le(*self, *other)
2189 }
2190 #[inline]
2191 fn gt(&self, other: &&mut B) -> bool {
2192 PartialOrd::gt(*self, *other)
2193 }
2194 #[inline]
2195 fn ge(&self, other: &&mut B) -> bool {
2196 PartialOrd::ge(*self, *other)
2197 }
2198 #[inline]
2199 fn __chaining_lt(&self, other: &&mut B) -> ControlFlow<bool> {
2200 PartialOrd::__chaining_lt(*self, *other)
2201 }
2202 #[inline]
2203 fn __chaining_le(&self, other: &&mut B) -> ControlFlow<bool> {
2204 PartialOrd::__chaining_le(*self, *other)
2205 }
2206 #[inline]
2207 fn __chaining_gt(&self, other: &&mut B) -> ControlFlow<bool> {
2208 PartialOrd::__chaining_gt(*self, *other)
2209 }
2210 #[inline]
2211 fn __chaining_ge(&self, other: &&mut B) -> ControlFlow<bool> {
2212 PartialOrd::__chaining_ge(*self, *other)
2213 }
2214 }
2215 #[stable(feature = "rust1", since = "1.0.0")]
2216 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2217 impl<A: PointeeSized> const Ord for &mut A
2218 where
2219 A: [const] Ord,
2220 {
2221 #[inline]
2222 fn cmp(&self, other: &Self) -> Ordering {
2223 Ord::cmp(*self, *other)
2224 }
2225 }
2226 #[stable(feature = "rust1", since = "1.0.0")]
2227 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2228 impl<A: PointeeSized> const Eq for &mut A where A: [const] Eq {}
2229
2230 #[stable(feature = "rust1", since = "1.0.0")]
2231 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2232 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&mut B> for &A
2233 where
2234 A: [const] PartialEq<B>,
2235 {
2236 #[inline]
2237 fn eq(&self, other: &&mut B) -> bool {
2238 PartialEq::eq(*self, *other)
2239 }
2240 #[inline]
2241 fn ne(&self, other: &&mut B) -> bool {
2242 PartialEq::ne(*self, *other)
2243 }
2244 }
2245
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2248 impl<A: PointeeSized, B: PointeeSized> const PartialEq<&B> for &mut A
2249 where
2250 A: [const] PartialEq<B>,
2251 {
2252 #[inline]
2253 fn eq(&self, other: &&B) -> bool {
2254 PartialEq::eq(*self, *other)
2255 }
2256 #[inline]
2257 fn ne(&self, other: &&B) -> bool {
2258 PartialEq::ne(*self, *other)
2259 }
2260 }
2261}