Skip to content

Commit

Permalink
Rollup merge of rust-lang#132268 - elichai:string_try_from_vec, r=Ama…
Browse files Browse the repository at this point in the history
…nieu

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>`)
  • Loading branch information
matthiaskrgr authored Feb 19, 2025
2 parents 84e9f29 + 0cd8694 commit 7b7b1d4
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 7b7b1d4

Please sign in to comment.