I was looking at the implementation of From<String>
for Rc<str>
and it is like this:
#[cfg(not(no_global_oom_handling))]
#[stable(feature = "shared_from_slice", since = "1.21.0")]
impl From<String> for Rc<str> {
/// Allocate a reference-counted string slice and copy `v` into it.
///
/// # Example
///
/// ```
/// # use std::rc::Rc;
/// let original: String = "statue".to_owned();
/// let shared: Rc<str> = Rc::from(original);
/// assert_eq!("statue", &shared[..]);
/// ```
#[inline]
fn from(v: String) -> Rc<str> {
Rc::from(&v[..])
}
}
The documentation mentions that it allocates a new string slice and copies v into it.
This seems a bit inefficient to me. A new slice is allocated, then the contents of v are copied to it, and then v is destroyed and hence deallocated. Why allocating again when the string already has the data? I think it should be possible to leak a pointer to the string and re-assign it via Rc::from_raw
, preventing a new allocation and a copy. What am I missing?