diff options
| author | Elichai Turkel <elichai.turkel@gmail.com> | 2024-10-28 17:28:47 +0200 |
|---|---|---|
| committer | Elichai Turkel <elichai.turkel@gmail.com> | 2024-10-28 17:28:47 +0200 |
| commit | 0cd8694128262d3fed4744d9629151776a6c5813 (patch) | |
| tree | b07e73ad7e22b3c0740a458f0a5f4d3ddf71d64d | |
| parent | 66701c42263042f7120385725606edeb987ad4f1 (diff) | |
| download | rust-0cd8694128262d3fed4744d9629151776a6c5813.tar.gz rust-0cd8694128262d3fed4744d9629151776a6c5813.zip | |
Impl TryFrom<Vec<u8>> for String
| -rw-r--r-- | library/alloc/src/string.rs | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index b042720933b..565947db145 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -3078,6 +3078,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 { |
