@@ -1419,7 +1419,9 @@ impl String {
14191419 pub fn push ( & mut self , ch : char ) {
14201420 match ch. len_utf8 ( ) {
14211421 1 => self . vec . push ( ch as u8 ) ,
1422- _ => self . vec . extend_from_slice ( ch. encode_utf8 ( & mut [ 0 ; 4 ] ) . as_bytes ( ) ) ,
1422+ _ => {
1423+ self . vec . extend_from_slice ( ch. encode_utf8 ( & mut [ 0 ; char:: MAX_LEN_UTF8 ] ) . as_bytes ( ) )
1424+ }
14231425 }
14241426 }
14251427
@@ -1716,7 +1718,7 @@ impl String {
17161718 #[ rustc_confusables( "set" ) ]
17171719 pub fn insert ( & mut self , idx : usize , ch : char ) {
17181720 assert ! ( self . is_char_boundary( idx) ) ;
1719- let mut bits = [ 0 ; 4 ] ;
1721+ let mut bits = [ 0 ; char :: MAX_LEN_UTF8 ] ;
17201722 let bits = ch. encode_utf8 ( & mut bits) . as_bytes ( ) ;
17211723
17221724 unsafe {
@@ -2797,7 +2799,7 @@ impl SpecToString for core::ascii::Char {
27972799impl SpecToString for char {
27982800 #[ inline]
27992801 fn spec_to_string ( & self ) -> String {
2800- String :: from ( self . encode_utf8 ( & mut [ 0 ; 4 ] ) )
2802+ String :: from ( self . encode_utf8 ( & mut [ 0 ; char :: MAX_LEN_UTF8 ] ) )
28012803 }
28022804}
28032805
@@ -3155,6 +3157,24 @@ impl From<String> for Vec<u8> {
31553157 }
31563158}
31573159
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+
31583178#[ cfg( not( no_global_oom_handling) ) ]
31593179#[ stable( feature = "rust1" , since = "1.0.0" ) ]
31603180impl fmt:: Write for String {
0 commit comments