Skip to content

Commit d5f89d2

Browse files
committed
Impl TryFrom<Vec<u8>> for String
1 parent bfe37cb commit d5f89d2

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

alloc/src/string.rs

+18
Original file line numberDiff line numberDiff line change
@@ -3078,6 +3078,24 @@ impl From<String> for Vec<u8> {
30783078
}
30793079
}
30803080

3081+
#[stable(feature = "try_from_vec_u8_for_string", since = "CURRENT_RUSTC_VERSION")]
3082+
impl TryFrom<Vec<u8>> for String {
3083+
type Error = FromUtf8Error;
3084+
/// Converts the given [`Vec<u8>`] into a [`String`] if it contains valid UTF-8 data.
3085+
///
3086+
/// # Examples
3087+
///
3088+
/// ```
3089+
/// let s1 = b"hello world".to_vec();
3090+
/// let v1 = String::try_from(s1).unwrap();
3091+
/// assert_eq!(v1, "hello world");
3092+
///
3093+
/// ```
3094+
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
3095+
Self::from_utf8(bytes)
3096+
}
3097+
}
3098+
30813099
#[cfg(not(no_global_oom_handling))]
30823100
#[stable(feature = "rust1", since = "1.0.0")]
30833101
impl fmt::Write for String {

0 commit comments

Comments
 (0)