Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Option::clone to Copy when possible #76551

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1228,22 +1228,36 @@ fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Option<T> {
#[inline]
fn clone(&self) -> Self {
default fn clone(&self) -> Self {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sure you check how specialization is used for iterators. As I understand it, it's always behind a helper trait so that specialization doesn't leak out into the public API (like I think this would).

match self {
Some(x) => Some(x.clone()),
None => None,
}
}

#[inline]
fn clone_from(&mut self, source: &Self) {
default fn clone_from(&mut self, source: &Self) {
match (self, source) {
(Some(to), Some(from)) => to.clone_from(from),
(to, from) => *to = from.clone(),
}
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Copy> Clone for Option<T> {
#[inline]
fn clone(&self) -> Self {
*self
}

#[inline]
fn clone_from(&mut self, source: &Self) {
*self = *source
}
}


#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Option<T> {
/// Returns [`None`][Option::None].
Expand Down