diff options
| author | Matthias Krüger <matthias.krueger@famsik.de> | 2025-02-19 21:16:02 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-02-19 21:16:02 +0100 |
| commit | 7b7b1d4ee9dc4c32f7f4bd9d24a5c6bcc23cca60 (patch) | |
| tree | e27ec0a508d81477b8cf85658df15db7161515ef | |
| parent | 84e9f2900758902fbbe6d09ec0f35546c220dedf (diff) | |
| parent | 0cd8694128262d3fed4744d9629151776a6c5813 (diff) | |
| download | rust-7b7b1d4ee9dc4c32f7f4bd9d24a5c6bcc23cca60.tar.gz rust-7b7b1d4ee9dc4c32f7f4bd9d24a5c6bcc23cca60.zip | |
Rollup merge of #132268 - elichai:string_try_from_vec, r=Amanieu
Impl TryFrom<Vec<u8>> for String I think this is useful enough to have :) As a general question, is there any policy around adding "missing" trait implementations? (like adding `AsRef<T> for T` for std types), I mostly stumble upon them when using a lot of "impl Trait in argument position" like (`foo: impl Into<String>`)
| -rw-r--r-- | library/alloc/src/string.rs | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 4a1ec0c9895..9446afd4b24 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -3157,6 +3157,24 @@ impl From<String> for Vec<u8> { } } +#[stable(feature = "try_from_vec_u8_for_string", since = "CURRENT_RUSTC_VERSION")] +impl TryFrom<Vec<u8>> for String { + type Error = FromUtf8Error; + /// Converts the given [`Vec<u8>`] into a [`String`] if it contains valid UTF-8 data. + /// + /// # Examples + /// + /// ``` + /// let s1 = b"hello world".to_vec(); + /// let v1 = String::try_from(s1).unwrap(); + /// assert_eq!(v1, "hello world"); + /// + /// ``` + fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { + Self::from_utf8(bytes) + } +} + #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Write for String { |
