Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does str::from_utf8() copy input data

Tags:

string

rust

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.

like image 960
SU3 Avatar asked Aug 09 '26 23:08

SU3


1 Answers

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.)

like image 81
cdhowie Avatar answered Aug 12 '26 15:08

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!