Skip to content

Commit 295bcdb

Browse files
committed
Override ToOwned::clone_into for Path and OsStr
The only non-overridden one remaining is the CStr impl, which cannot be optimized as doing so would break CString's second invariant.
1 parent 9f2abad commit 295bcdb

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

src/libstd/ffi/os_str.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -677,7 +677,13 @@ impl Borrow<OsStr> for OsString {
677677
#[stable(feature = "rust1", since = "1.0.0")]
678678
impl ToOwned for OsStr {
679679
type Owned = OsString;
680-
fn to_owned(&self) -> OsString { self.to_os_string() }
680+
fn to_owned(&self) -> OsString {
681+
self.to_os_string()
682+
}
683+
fn clone_into(&self, target: &mut OsString) {
684+
target.clear();
685+
target.push(self);
686+
}
681687
}
682688

683689
#[stable(feature = "rust1", since = "1.0.0")]
@@ -863,4 +869,14 @@ mod tests {
863869
let boxed = <Box<OsStr>>::default();
864870
assert!(boxed.is_empty());
865871
}
872+
873+
#[test]
874+
fn test_os_str_clone_into() {
875+
let mut os_string = OsString::with_capacity(123);
876+
os_string.push("hello");
877+
let os_str = OsStr::new("bonjour");
878+
os_str.clone_into(&mut os_string);
879+
assert_eq!(os_str, os_string);
880+
assert!(os_string.capacity() >= 123);
881+
}
866882
}

src/libstd/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,7 @@
311311
#![feature(str_utf16)]
312312
#![feature(test, rustc_private)]
313313
#![feature(thread_local)]
314+
#![feature(toowned_clone_into)]
314315
#![feature(try_from)]
315316
#![feature(unboxed_closures)]
316317
#![feature(unicode)]

src/libstd/path.rs

+12
Original file line numberDiff line numberDiff line change
@@ -1322,6 +1322,9 @@ impl ToOwned for Path {
13221322
fn to_owned(&self) -> PathBuf {
13231323
self.to_path_buf()
13241324
}
1325+
fn clone_into(&self, target: &mut PathBuf) {
1326+
self.inner.clone_into(&mut target.inner);
1327+
}
13251328
}
13261329

13271330
#[stable(feature = "rust1", since = "1.0.0")]
@@ -3722,4 +3725,13 @@ mod tests {
37223725
assert_eq!(&*boxed, &*path_buf);
37233726
assert_eq!(&*path_buf, path);
37243727
}
3728+
3729+
#[test]
3730+
fn test_clone_into() {
3731+
let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
3732+
let path = Path::new("short");
3733+
path.clone_into(&mut path_buf);
3734+
assert_eq!(path, path_buf);
3735+
assert!(path_buf.into_os_string().capacity() >= 15);
3736+
}
37253737
}

0 commit comments

Comments
 (0)