Add an example of lossy decoding to str::Utf8Error docs
This commit is contained in:
parent
cc34ca1c97
commit
e09dbbc39e
1 changed files with 31 additions and 0 deletions
|
|
@ -165,6 +165,37 @@ Section: Creating a string
|
|||
///
|
||||
/// [`String`]: ../../std/string/struct.String.html#method.from_utf8
|
||||
/// [`&str`]: ../../std/str/fn.from_utf8.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// This error type’s methods can be used to create functionality
|
||||
/// similar to `String::from_utf8_lossy` without allocating heap memory:
|
||||
///
|
||||
/// ```
|
||||
/// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
|
||||
/// loop {
|
||||
/// match ::std::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 let Some(invalid_sequence_length) = error.error_len() {
|
||||
/// input = &after_valid[invalid_sequence_length..]
|
||||
/// } else {
|
||||
/// break
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Copy, Eq, PartialEq, Clone, Debug)]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub struct Utf8Error {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue