Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Is this use of Copy sound?
I've heard people say that the copy of a Copy type is guaranteed to be just a memcpy. This blog is one such example but I've seen many others as well.
This doesn't sound right to me because copy is a safe trait which means Rust shouldn't be allowed to make such an assumption. The code below compiles which seems to support my intuition but it requires unsafe so I don't know for sure whether this is actually allowed or not.
struct MyString {
ptr: *const u8,
len: usize,
cap: usize,
}
impl Clone for MyString {
fn clone (&self) -> Self {
let string = unsafe{String::from_raw_parts(self.ptr as *mut _, self.len, self.cap)};
let new_string = string.clone();
let (ptr, len, cap) = (string.as_ptr(), string.len(), string.capacity());
std::mem::forget(string);
std::mem::forget(new_string);
Self {
ptr,
len,
cap
}
}
}
impl Copy for MyString {}
Ignoring the leaked strings, is this code actually sound?
As far as I can understand, the real distinction between non-Copy and Copy types is that Copy types are not allowed to have drop, whether it is drop glue (so no fields that are not copy) or an explicit drop. Is this intuition correct?
9 posts - 4 participants
🏷️ rust_feed