diff options
| author | kennytm <kennytm@gmail.com> | 2018-03-22 23:20:11 +0800 |
|---|---|---|
| committer | kennytm <kennytm@gmail.com> | 2018-03-22 23:20:11 +0800 |
| commit | 2b9674d2b1f0e2caa95f64bb37107063d3d95863 (patch) | |
| tree | 79634b7c506140285f19e0bdef38018062ba14b5 | |
| parent | a4bc8590117f313ab2c895ab91f183f368369e2b (diff) | |
| parent | e09dbbc39eeecbf6a8122d86297a1e8701aca26b (diff) | |
| download | rust-2b9674d2b1f0e2caa95f64bb37107063d3d95863.tar.gz rust-2b9674d2b1f0e2caa95f64bb37107063d3d95863.zip | |
Rollup merge of #49105 - SimonSapin:from_utf8_lossy_example, r=alexcrichton
Add an example of lossy decoding to str::Utf8Error docs CC https://github.com/rust-lang/rust/issues/33906
| -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 { |
