Skip to content

Commit 36e048a

Browse files
committed
Manually implement PartialOrd/Ord for Option
1 parent d7a166a commit 36e048a

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

library/core/src/option.rs

+31-2
Original file line numberDiff line numberDiff line change
@@ -557,13 +557,13 @@ use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
557557
use crate::panicking::{panic, panic_str};
558558
use crate::pin::Pin;
559559
use crate::{
560-
convert, hint, mem,
560+
cmp, convert, hint, mem,
561561
ops::{self, ControlFlow, Deref, DerefMut},
562562
slice,
563563
};
564564

565565
/// The `Option` type. See [the module level documentation](self) for more.
566-
#[derive(Copy, PartialOrd, Eq, Ord, Debug, Hash)]
566+
#[derive(Copy, Eq, Debug, Hash)]
567567
#[rustc_diagnostic_item = "Option"]
568568
#[lang = "Option"]
569569
#[stable(feature = "rust1", since = "1.0.0")]
@@ -2162,6 +2162,35 @@ impl<T: PartialEq> PartialEq for Option<T> {
21622162
}
21632163
}
21642164

2165+
// Manually implementing here somewhat improves codegen for
2166+
// https://github.com/rust-lang/rust/issues/49892, although still
2167+
// not optimal.
2168+
#[stable(feature = "rust1", since = "1.0.0")]
2169+
impl<T: PartialOrd> PartialOrd for Option<T> {
2170+
#[inline]
2171+
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
2172+
match (self, other) {
2173+
(Some(l), Some(r)) => l.partial_cmp(r),
2174+
(Some(_), None) => Some(cmp::Ordering::Greater),
2175+
(None, Some(_)) => Some(cmp::Ordering::Less),
2176+
(None, None) => Some(cmp::Ordering::Equal),
2177+
}
2178+
}
2179+
}
2180+
2181+
#[stable(feature = "rust1", since = "1.0.0")]
2182+
impl<T: Ord> Ord for Option<T> {
2183+
#[inline]
2184+
fn cmp(&self, other: &Self) -> cmp::Ordering {
2185+
match (self, other) {
2186+
(Some(l), Some(r)) => l.cmp(r),
2187+
(Some(_), None) => cmp::Ordering::Greater,
2188+
(None, Some(_)) => cmp::Ordering::Less,
2189+
(None, None) => cmp::Ordering::Equal,
2190+
}
2191+
}
2192+
}
2193+
21652194
/////////////////////////////////////////////////////////////////////////////
21662195
// The Option Iterators
21672196
/////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)