Skip to content

Commit f8fd23a

Browse files
committed
Manually implement PartialOrd/Ord for Option
1 parent 5f254d8 commit f8fd23a

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")]
@@ -2165,6 +2165,35 @@ impl<T: PartialEq> PartialEq for Option<T> {
21652165
}
21662166
}
21672167

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

0 commit comments

Comments
 (0)