Skip to content

Commit 353bdb3

Browse files
authored
Rollup merge of rust-lang#40290 - 3Hren:master, r=aturon
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. Personally without this change I ended with `Result<String, (Vec<u8>, Utf8Error)`, which almost copies the functionality of `FromUtf8Error`, but allows immutable view access.
2 parents c398efc + bbdf190 commit 353bdb3

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

src/doc/unstable-book/src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979
- [fmt_internals](fmt-internals.md)
8080
- [fn_traits](fn-traits.md)
8181
- [fnbox](fnbox.md)
82+
- [from_utf8_error_as_bytes](from_utf8_error_as_bytes.md)
8283
- [fundamental](fundamental.md)
8384
- [fused](fused.md)
8485
- [future_atomic_orderings](future-atomic-orderings.md)
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# `from_utf8_error_as_bytes`
2+
3+
The tracking issue for this feature is: [#40895]
4+
5+
[#40895]: https://github.com/rust-lang/rust/issues/40895
6+
7+
------------------------

src/libcollections/string.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1403,6 +1403,26 @@ 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+
/// #![feature(from_utf8_error_as_bytes)]
1414+
/// // some invalid bytes, in a vector
1415+
/// let bytes = vec![0, 159];
1416+
///
1417+
/// let value = String::from_utf8(bytes);
1418+
///
1419+
/// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1420+
/// ```
1421+
#[unstable(feature = "from_utf8_error_as_bytes", reason = "recently added", issue = "40895")]
1422+
pub fn as_bytes(&self) -> &[u8] {
1423+
&self.bytes[..]
1424+
}
1425+
14061426
/// Returns the bytes that were attempted to convert to a `String`.
14071427
///
14081428
/// This method is carefully constructed to avoid allocation. It will

0 commit comments

Comments
 (0)