diff options
| author | Josh Stone <jistone@redhat.com> | 2020-03-20 15:42:56 -0700 |
|---|---|---|
| committer | Josh Stone <jistone@redhat.com> | 2020-04-06 18:26:37 -0700 |
| commit | b80fa76ee0a160fffa04e337b8e33ef655a80649 (patch) | |
| tree | a205766bb316383a2b1f50f6f6d3090f10aa3f9e /src/libstd | |
| parent | e8339e820b0c4e7c9a26a3e3495b7655e60bd102 (diff) | |
| download | rust-b80fa76ee0a160fffa04e337b8e33ef655a80649.tar.gz rust-b80fa76ee0a160fffa04e337b8e33ef655a80649.zip | |
Implement ToOwned::clone_into for CStr
It can try to keep its allocation by converting the inner `Box` to `Vec`, using `clone_into` on the bytes, then convert back to `Box`.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/ffi/c_str.rs | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 04eaba515ff..0a4802fb2c8 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -1329,6 +1329,12 @@ impl ToOwned for CStr { fn to_owned(&self) -> CString { CString { inner: self.to_bytes_with_nul().into() } } + + fn clone_into(&self, target: &mut CString) { + let mut b = Vec::from(mem::take(&mut target.inner)); + self.to_bytes_with_nul().clone_into(&mut b); + target.inner = b.into_boxed_slice(); + } } #[stable(feature = "cstring_asref", since = "1.7.0")] @@ -1511,6 +1517,17 @@ mod tests { } #[test] + fn test_c_str_clone_into() { + let mut c_string = CString::new("lorem").unwrap(); + let c_ptr = c_string.as_ptr(); + let c_str = CStr::from_bytes_with_nul(b"ipsum\0").unwrap(); + c_str.clone_into(&mut c_string); + assert_eq!(c_str, c_string.as_c_str()); + // The exact same size shouldn't have needed to move its allocation + assert_eq!(c_ptr, c_string.as_ptr()); + } + + #[test] fn into_rc() { let orig: &[u8] = b"Hello, world!\0"; let cstr = CStr::from_bytes_with_nul(orig).unwrap(); |
