Skip to content

Commit e78b619

Browse files
elichaigitbot
authored and
gitbot
committed
Impl TryFrom<Vec<u8>> for String
1 parent 0e6d410 commit e78b619

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
@@ -3157,6 +3157,24 @@ impl From<String> for Vec<u8> {
31573157
}
31583158
}
31593159

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

0 commit comments

Comments
 (0)