Does std::str::from_utf8(v: &[u8])
copy the input byte array?
The documentation is a bit ambiguous. It talks about conversion, and I'm not sure if by that they mean just changing the reference type or that the data may be transformed, which would require copying it. They don't explicitly state that no copy occurs.
No copy occurs.
The signature actually tells you this. If we explicitly specify the elided lifetimes, we get:
pub const fn from_utf8<'a>(v: &'a [u8]) -> Result<&'a str, Utf8Error>
This communicates that the returned &str
borrows from the input.
It's worth noting that a &str
is effectively just a &[u8]
that is guaranteed to be valid UTF-8. They even have the same representation in memory, so the conversion from one to the other has zero runtime overhead -- the body of from_utf8_unchecked
is literally just unsafe { mem::transmute(v) }
. (Obviously the UTF-8 validation that from_utf8
performs does have runtime cost, but the conversion afterwards is effectively a no-op.)