Skip to content

Commit

Permalink
Rollup merge of rust-lang#49105 - SimonSapin:from_utf8_lossy_example,…
Browse files Browse the repository at this point in the history
… r=alexcrichton

Add an example of lossy decoding to str::Utf8Error docs

CC rust-lang#33906
  • Loading branch information
kennytm committed Mar 22, 2018
2 parents a4bc859 + e09dbbc commit 2b9674d
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/libcore/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 2b9674d

Please sign in to comment.