From 0cd8694128262d3fed4744d9629151776a6c5813 Mon Sep 17 00:00:00 2001 From: Elichai Turkel Date: Mon, 28 Oct 2024 17:28:47 +0200 Subject: [PATCH] Impl TryFrom> for String --- library/alloc/src/string.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index b042720933b6d..565947db14587 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -3078,6 +3078,24 @@ impl From for Vec { } } +#[stable(feature = "try_from_vec_u8_for_string", since = "CURRENT_RUSTC_VERSION")] +impl TryFrom> for String { + type Error = FromUtf8Error; + /// Converts the given [`Vec`] 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) -> Result { + Self::from_utf8(bytes) + } +} + #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Write for String {