pub struct Utf8Error {/* private fields */ }Expand description
Errors which can occur when attempting to interpret a sequence ofu8as a string.
As such, thefrom_utf8 family of functions and methods for bothStringsand&strs make use of this error, for example.
§Examples
This error type’s methods can be used to create functionalitysimilar toString::from_utf8_lossy without allocating heap memory:
fnfrom_utf8_lossy<F>(mutinput:&[u8],mutpush: F)whereF: FnMut(&str) {loop{matchstd::str::from_utf8(input) {Ok(valid) => { push(valid);break}Err(error) => {let(valid, after_valid) = input.split_at(error.valid_up_to());unsafe{ push(std::str::from_utf8_unchecked(valid)) } push("\u{FFFD}");if letSome(invalid_sequence_length) = error.error_len() { input =&after_valid[invalid_sequence_length..] }else{break} } } }}Implementations§
Source§implUtf8Error
implUtf8Error
1.5.0 (const: 1.63.0) ·Sourcepub const fnvalid_up_to(&self) ->usize
pub const fnvalid_up_to(&self) ->usize
Returns the index in the given string up to which valid UTF-8 wasverified.
It is the maximum index such thatfrom_utf8(&input[..index])would returnOk(_).
§Examples
Basic usage:
1.20.0 (const: 1.63.0) ·Sourcepub const fnerror_len(&self) ->Option<usize>
pub const fnerror_len(&self) ->Option<usize>
Provides more information about the failure:
None: the end of the input was reached unexpectedly.self.valid_up_to()is 1 to 3 bytes from the end of the input.If a byte stream (such as a file or a network socket) is being decoded incrementally,this could be a validcharwhose UTF-8 byte sequence is spanning multiple chunks.Some(len): an unexpected byte was encountered.The length provided is that of the invalid byte sequencethat starts at the index given byvalid_up_to().Decoding should resume after that sequence(after inserting aU+FFFD REPLACEMENT CHARACTER) in case oflossy decoding.