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 all commits
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
32 changes: 28 additions & 4 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@
use crate::iter::{FromIterator, FusedIterator, TrustedLen};
use crate::pin::Pin;
use crate::{
convert, fmt, hint, mem,
ops::{self, Deref, DerefMut},
convert, fmt, hint, mem, ptr,
ops::{self, Deref, DerefMut, Range},
};

/// The `Option` type. See [the module level documentation](self) for more.
Expand Down Expand Up @@ -1228,22 +1228,46 @@ 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
}
}

// Range<T> is not Copy even if T is copy (see #27186),
// so provide an efficient implementation.
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Copy> Clone for Option<Range<T>> {
#[inline]
fn clone(&self) -> Self {
// SAFETY: 'self' is not Drop so memcpy is OK.
unsafe { ptr::read(self as *const Self) }
}
}

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