Skip to content

Commit 5a09d7c

Browse files
committed
Add as_bytes() for FromUtf8Error.
This change allows to obtain an underlying invalid UTF-8 bytes without `FromUtf8Error` destruction. Such method may be useful for example in a library that attempts to save both valid and invalid UTF-8 strings in some struct and to be able to provide immutable access to it without destruction.
1 parent 4f32e0d commit 5a09d7c

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/libcollections/string.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1403,6 +1403,25 @@ impl String {
14031403
}
14041404

14051405
impl FromUtf8Error {
1406+
/// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1407+
///
1408+
/// # Examples
1409+
///
1410+
/// Basic usage:
1411+
///
1412+
/// ```
1413+
/// // some invalid bytes, in a vector
1414+
/// let bytes = vec![0, 159];
1415+
///
1416+
/// let value = String::from_utf8(bytes);
1417+
///
1418+
/// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1419+
/// ```
1420+
#[unstable(feature = "from_utf8_error_as_bytes", issue = "40895")]
1421+
pub fn as_bytes(&self) -> &[u8] {
1422+
&self.bytes[..]
1423+
}
1424+
14061425
/// Returns the bytes that were attempted to convert to a `String`.
14071426
///
14081427
/// This method is carefully constructed to avoid allocation. It will

0 commit comments

Comments
 (0)