Skip to content

Commit 2b9674d

Browse files
committed
Rollup merge of #49105 - SimonSapin:from_utf8_lossy_example, r=alexcrichton
Add an example of lossy decoding to str::Utf8Error docs CC #33906
2 parents a4bc859 + e09dbbc commit 2b9674d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/libcore/str/mod.rs

+31
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,37 @@ Section: Creating a string
165165
///
166166
/// [`String`]: ../../std/string/struct.String.html#method.from_utf8
167167
/// [`&str`]: ../../std/str/fn.from_utf8.html
168+
///
169+
/// # Examples
170+
///
171+
/// This error type’s methods can be used to create functionality
172+
/// similar to `String::from_utf8_lossy` without allocating heap memory:
173+
///
174+
/// ```
175+
/// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
176+
/// loop {
177+
/// match ::std::str::from_utf8(input) {
178+
/// Ok(valid) => {
179+
/// push(valid);
180+
/// break
181+
/// }
182+
/// Err(error) => {
183+
/// let (valid, after_valid) = input.split_at(error.valid_up_to());
184+
/// unsafe {
185+
/// push(::std::str::from_utf8_unchecked(valid))
186+
/// }
187+
/// push("\u{FFFD}");
188+
///
189+
/// if let Some(invalid_sequence_length) = error.error_len() {
190+
/// input = &after_valid[invalid_sequence_length..]
191+
/// } else {
192+
/// break
193+
/// }
194+
/// }
195+
/// }
196+
/// }
197+
/// }
198+
/// ```
168199
#[derive(Copy, Eq, PartialEq, Clone, Debug)]
169200
#[stable(feature = "rust1", since = "1.0.0")]
170201
pub struct Utf8Error {

0 commit comments

Comments
 (0)