1
Fork 0

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>`)
This commit is contained in:
Matthias Krüger 2025-02-19 21:16:02 +01:00 committed by GitHub
commit 7b7b1d4ee9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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 {