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