Skip to content

Commit 96aa2ce

Browse files
authored
Rollup merge of rust-lang#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>`)
2 parents facdfaa + 0cd8694 commit 96aa2ce

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

library/alloc/src/string.rs

+18
Original file line numberDiff line numberDiff line change
@@ -3155,6 +3155,24 @@ impl From<String> for Vec<u8> {
31553155
}
31563156
}
31573157

3158+
#[stable(feature = "try_from_vec_u8_for_string", since = "CURRENT_RUSTC_VERSION")]
3159+
impl TryFrom<Vec<u8>> for String {
3160+
type Error = FromUtf8Error;
3161+
/// Converts the given [`Vec<u8>`] into a [`String`] if it contains valid UTF-8 data.
3162+
///
3163+
/// # Examples
3164+
///
3165+
/// ```
3166+
/// let s1 = b"hello world".to_vec();
3167+
/// let v1 = String::try_from(s1).unwrap();
3168+
/// assert_eq!(v1, "hello world");
3169+
///
3170+
/// ```
3171+
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
3172+
Self::from_utf8(bytes)
3173+
}
3174+
}
3175+
31583176
#[cfg(not(no_global_oom_handling))]
31593177
#[stable(feature = "rust1", since = "1.0.0")]
31603178
impl fmt::Write for String {

0 commit comments

Comments
 (0)