From f8fd23a2add24de796b2fab197920d3fd349941a Mon Sep 17 00:00:00 2001 From: clubby789 Date: Tue, 5 Mar 2024 14:51:48 +0000 Subject: [PATCH] Manually implement `PartialOrd`/`Ord` for `Option` --- library/core/src/option.rs | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 4ddf68c12d3..0083d15efae 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -557,13 +557,13 @@ use crate::panicking::{panic, panic_str}; use crate::pin::Pin; use crate::{ - convert, hint, mem, + cmp, convert, hint, mem, ops::{self, ControlFlow, Deref, DerefMut}, slice, }; /// The `Option` type. See [the module level documentation](self) for more. -#[derive(Copy, PartialOrd, Eq, Ord, Debug, Hash)] +#[derive(Copy, Eq, Debug, Hash)] #[rustc_diagnostic_item = "Option"] #[lang = "Option"] #[stable(feature = "rust1", since = "1.0.0")] @@ -2165,6 +2165,35 @@ fn eq(&self, other: &Self) -> bool { } } +// Manually implementing here somewhat improves codegen for +// https://github.com/rust-lang/rust/issues/49892, although still +// not optimal. +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialOrd for Option { + #[inline] + fn partial_cmp(&self, other: &Self) -> Option { + match (self, other) { + (Some(l), Some(r)) => l.partial_cmp(r), + (Some(_), None) => Some(cmp::Ordering::Greater), + (None, Some(_)) => Some(cmp::Ordering::Less), + (None, None) => Some(cmp::Ordering::Equal), + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Ord for Option { + #[inline] + fn cmp(&self, other: &Self) -> cmp::Ordering { + match (self, other) { + (Some(l), Some(r)) => l.cmp(r), + (Some(_), None) => cmp::Ordering::Greater, + (None, Some(_)) => cmp::Ordering::Less, + (None, None) => cmp::Ordering::Equal, + } + } +} + ///////////////////////////////////////////////////////////////////////////// // The Option Iterators /////////////////////////////////////////////////////////////////////////////