mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-22 14:55:26 +00:00
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`.
This commit is contained in:
parent
e8339e820b
commit
b80fa76ee0
@ -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")]
|
||||
@ -1510,6 +1516,17 @@ mod tests {
|
||||
assert_eq!(boxed.to_bytes_with_nul(), &[0]);
|
||||
}
|
||||
|
||||
#[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";
|
||||
|
Loading…
Reference in New Issue
Block a user