pub fn with_str_bytes<R, F>(s: &mut str, f: F) -> R
Expand description
Executes a function on the bytes of a string, asserting that it is valid UTF-8.
§Panics
This will panic if the function causes the string to become invalid UTF-8. In this case, the bytes up to the point of the first invalid UTF-8 byte will remain the same, and the contents of the rest of the string is unspecified, although it will be valid UTF-8.
If the callback itself panics, the entire string’s contents is unspecified, but it will be valid UTF-8. Even if the byte slice was set to invalid UTF-8, there will not be a double panic.
§Examples
Replace all spaces in a string with dashes in-place:
let mut data: Box<str> = Box::from("Lorem ipsum dolor sit amet");
with_str_bytes::with_str_bytes(&mut data, |bytes| {
for byte in bytes {
if *byte == b' ' {
*byte = b'-';
}
}
});
assert_eq!(&*data, "Lorem-ipsum-dolor-sit-amet");