diff options
| author | Corey Farwell <coreyf@rwell.org> | 2017-04-18 14:05:42 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-04-18 14:05:42 -0400 |
| commit | 353bdb30e35aa03cc3055505687eb77b304441b1 (patch) | |
| tree | 81327e3b29267a72de6973f2a15b56b879c4ab26 /src/libcollections | |
| parent | c398efc53f09f6e1a8cba4ec2259ffb9d89f0542 (diff) | |
| parent | bbdf190c6a2d5bc095c8d3addff0868395bff31f (diff) | |
| download | rust-353bdb30e35aa03cc3055505687eb77b304441b1.tar.gz rust-353bdb30e35aa03cc3055505687eb77b304441b1.zip | |
Rollup merge of #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.
Diffstat (limited to 'src/libcollections')
| -rw-r--r-- | src/libcollections/string.rs | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 7d9d7276201..8d6cf305112 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -1403,6 +1403,26 @@ impl String { } impl FromUtf8Error { + /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(from_utf8_error_as_bytes)] + /// // some invalid bytes, in a vector + /// let bytes = vec![0, 159]; + /// + /// let value = String::from_utf8(bytes); + /// + /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes()); + /// ``` + #[unstable(feature = "from_utf8_error_as_bytes", reason = "recently added", issue = "40895")] + pub fn as_bytes(&self) -> &[u8] { + &self.bytes[..] + } + /// Returns the bytes that were attempted to convert to a `String`. /// /// This method is carefully constructed to avoid allocation. It will |
