Skip to content

impl Clone for Cow #19359

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

Merged
merged 1 commit into from
Dec 5, 2014
Merged
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
12 changes: 12 additions & 0 deletions src/libcore/borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,18 @@ pub enum Cow<'a, T, Sized? B: 'a> where B: ToOwned<T> {
Owned(T)
}

impl<'a, T, Sized? B> Clone for Cow<'a, T, B> where B: ToOwned<T> {
fn clone(&self) -> Cow<'a, T, B> {
match *self {
Borrowed(b) => Borrowed(b),
Owned(ref o) => {
let b: &B = BorrowFrom::borrow_from(o);
Owned(b.to_owned())
Copy link
Contributor

Choose a reason for hiding this comment

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

I must confess that it feels weird to me to always into_owned a Clone of an owned Cow. I imagine that always producing a Borrow would have unfortunate consequences? Can you provide an example?

Copy link
Member Author

Choose a reason for hiding this comment

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

If Self = SendStr = CowString<'static>. Cloning that can't return a Borrowed value, since that would need an inner &'static str, and you can't produce &'static str from String.

Copy link
Contributor

Choose a reason for hiding this comment

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

Should we explicitly document the behaviour, since it's subtle and might be unexpected? Or do you think it can be considered an implementation detail?

Copy link
Member

Choose a reason for hiding this comment

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

Another option would be to require T: Clone instead of B: BorrowFrom<T> so you could just call .clone() on the owned variant (which may be more expected)

Copy link
Member Author

Choose a reason for hiding this comment

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

require T: Clone instead of B: BorrowFrom

Note that the Cow struct enforces the B: BorrowFrom<T> bound, so it can't be removed. I wrote the impl in this way to reduce the numbers of bounds on the input parameters.

},
}
}
}

impl<'a, T, Sized? B> Cow<'a, T, B> where B: ToOwned<T> {
/// Acquire a mutable reference to the owned form of the data.
///
Expand Down