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 #76552

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

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