pub(super) unsafe fn append_to_string<F>(
buf: &mut String,
f: F,
) -> Result<usize>🔬This is a nightly-only experimental API. (
alloc_io #154046)Expand description
Several read_to_string and read_line methods in the standard library will
append data into a String buffer, but we need to be pretty careful when
doing this. The implementation will just call .as_mut_vec() and then
delegate to a byte-oriented reading method, but we must ensure that when
returning we never leave buf in a state such that it contains invalid UTF-8
in its bounds.
To this end, we use an RAII guard (to protect against panics) which updates the length of the string when it is dropped. This guard initially truncates the string to the prior length and only after we’ve validated that the new contents are valid UTF-8 do we allow it to set a longer length.
The unsafety in this function is twofold:
- We’re looking at the raw bytes of
buf, so we take on the burden of UTF-8 checks. - We’re passing a raw buffer to the function
f, and it is expected that the function only appends bytes to the buffer. We’ll get undefined behavior if existing bytes are overwritten to have non-UTF-8 data.