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