diff options
| author | Simon Sapin <simon.sapin@exyr.org> | 2018-03-17 10:05:23 +0100 |
|---|---|---|
| committer | Simon Sapin <simon.sapin@exyr.org> | 2018-03-17 11:17:11 +0100 |
| commit | e09dbbc39eeecbf6a8122d86297a1e8701aca26b (patch) | |
| tree | d4be529a9124e90e44b35cdf84c4427e3bed3556 | |
| parent | cc34ca1c9787fde84116637a0cee92fc5e375e3d (diff) | |
| download | rust-e09dbbc39eeecbf6a8122d86297a1e8701aca26b.tar.gz rust-e09dbbc39eeecbf6a8122d86297a1e8701aca26b.zip | |
Add an example of lossy decoding to str::Utf8Error docs
| -rw-r--r-- | src/libcore/str/mod.rs | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 9cf862bd936..1185b7acaae 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -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 { |
