@@ -479,16 +479,15 @@ impl String {
479
479
}
480
480
}
481
481
482
- /// Converts a slice of bytes to a `String` , including invalid characters.
482
+ /// Converts a slice of bytes to a string , including invalid characters.
483
483
///
484
- /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a slice of
485
- /// bytes ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
486
- /// the two. Not all byte slices are valid string slices , however: [`&str`]
487
- /// requires that it is valid UTF-8. During this conversion,
484
+ /// Strings are made of bytes ([`u8`]), and a slice of bytes
485
+ /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
486
+ /// between the two. Not all byte slices are valid strings , however: strings
487
+ /// are required to be valid UTF-8. During this conversion,
488
488
/// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
489
489
/// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
490
490
///
491
- /// [`&str`]: ../primitive.str.html
492
491
/// [`u8`]: ../primitive.u8.html
493
492
/// [byteslice]: ../primitive.slice.html
494
493
///
@@ -499,10 +498,13 @@ impl String {
499
498
///
500
499
/// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
501
500
///
502
- /// If you need a [`&str`] instead of a `String`, consider
503
- /// [`str::from_utf8()`].
501
+ /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
502
+ /// UTF-8, then we need to insert the replacement characters, which will
503
+ /// change the size of the string, and hence, require a `String`. But if
504
+ /// it's already valid UTF-8, we don't need a new allocation. This return
505
+ /// type allows us to handle both cases.
504
506
///
505
- /// [`str::from_utf8() `]: ../str/fn.from_utf8 .html
507
+ /// [`Cow<'a, str> `]: ../borrow/enum.Cow .html
506
508
///
507
509
/// # Examples
508
510
///
@@ -512,8 +514,7 @@ impl String {
512
514
/// // some bytes, in a vector
513
515
/// let sparkle_heart = vec![240, 159, 146, 150];
514
516
///
515
- /// // We know these bytes are valid, so we'll use `unwrap()`.
516
- /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
517
+ /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
517
518
///
518
519
/// assert_eq!("💖", sparkle_heart);
519
520
/// ```
0 commit comments