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