@@ -1419,7 +1419,9 @@ impl String {
1419
1419
pub fn push ( & mut self , ch : char ) {
1420
1420
match ch. len_utf8 ( ) {
1421
1421
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
+ }
1423
1425
}
1424
1426
}
1425
1427
@@ -1716,7 +1718,7 @@ impl String {
1716
1718
#[ rustc_confusables( "set" ) ]
1717
1719
pub fn insert ( & mut self , idx : usize , ch : char ) {
1718
1720
assert ! ( self . is_char_boundary( idx) ) ;
1719
- let mut bits = [ 0 ; 4 ] ;
1721
+ let mut bits = [ 0 ; char :: MAX_LEN_UTF8 ] ;
1720
1722
let bits = ch. encode_utf8 ( & mut bits) . as_bytes ( ) ;
1721
1723
1722
1724
unsafe {
@@ -2797,7 +2799,7 @@ impl SpecToString for core::ascii::Char {
2797
2799
impl SpecToString for char {
2798
2800
#[ inline]
2799
2801
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 ] ) )
2801
2803
}
2802
2804
}
2803
2805
@@ -3155,6 +3157,24 @@ impl From<String> for Vec<u8> {
3155
3157
}
3156
3158
}
3157
3159
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
+
3158
3178
#[ cfg( not( no_global_oom_handling) ) ]
3159
3179
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
3160
3180
impl fmt:: Write for String {
0 commit comments