Two very different String methods for the same job?

Afaict, these inline and optimize to identical asm. Is there some compiler-stdlib magic whereby the 2nd taps into the 1st?

Or: The 2nd suggests that the 3 String usizes are optimized to be such that their first 2 can dual-purpose also serve as an str fat pointer. But then, why not do the same in the 1st case? That would at least elimitate an `unsafe’.

pub const fn as_str(&self) -> &str {
    // SAFETY: String contents are stipulated to be valid UTF-8, invalid contents are an error
    // at construction.
    unsafe { str::from_utf8_unchecked(self.vec.as_slice()) }
}

impl AsRef<str> for String {
    #[inline]
    fn as_ref(&self) -> &str {
        self
    }
}

The compiler–stdlib magic (deref coercion) happens in as_ref which implicitly calls the Deref impl. As such, all of &string, string.as_ref(), and string.as_str() end up executing the same code.

2 Likes