33use std:: borrow:: Cow ;
44
55#[ cfg( feature = "encoding" ) ]
6- use encoding_rs:: { Encoding , UTF_16BE , UTF_16LE , UTF_8 } ;
6+ use encoding_rs:: { DecoderResult , Encoding , UTF_16BE , UTF_16LE , UTF_8 } ;
77
88#[ cfg( feature = "encoding" ) ]
99use crate :: Error ;
@@ -88,6 +88,17 @@ impl Decoder {
8888
8989 decoded
9090 }
91+
92+ /// Like [`decode`][Self::decode] but using a pre-allocated buffer.
93+ pub fn decode_into ( & self , bytes : & [ u8 ] , buf : & mut String ) -> Result < ( ) > {
94+ #[ cfg( not( feature = "encoding" ) ) ]
95+ buf. push_str ( std:: str:: from_utf8 ( bytes) ?) ;
96+
97+ #[ cfg( feature = "encoding" ) ]
98+ decode_into ( bytes, self . encoding , buf) ?;
99+
100+ Ok ( ( ) )
101+ }
91102}
92103
93104/// Decodes the provided bytes using the specified encoding.
@@ -100,6 +111,34 @@ pub fn decode<'b>(bytes: &'b [u8], encoding: &'static Encoding) -> Result<Cow<'b
100111 . ok_or ( Error :: NonDecodable ( None ) )
101112}
102113
114+ /// Like [`decode`] but using a pre-allocated buffer.
115+ #[ cfg( feature = "encoding" ) ]
116+ pub fn decode_into ( bytes : & [ u8 ] , encoding : & ' static Encoding , buf : & mut String ) -> Result < ( ) > {
117+ if encoding == UTF_8 {
118+ buf. push_str ( std:: str:: from_utf8 ( bytes) ?) ;
119+ return Ok ( ( ) ) ;
120+ }
121+
122+ let mut decoder = encoding. new_decoder_without_bom_handling ( ) ;
123+ buf. reserve (
124+ decoder
125+ . max_utf8_buffer_length_without_replacement ( bytes. len ( ) )
126+ // SAFETY: None can be returned only if required size will overflow usize,
127+ // but in that case String::reserve also panics
128+ . unwrap ( ) ,
129+ ) ;
130+ let ( result, read) = decoder. decode_to_string_without_replacement ( bytes, buf, true ) ;
131+ match result {
132+ DecoderResult :: InputEmpty => {
133+ debug_assert_eq ! ( read, bytes. len( ) ) ;
134+ Ok ( ( ) )
135+ }
136+ DecoderResult :: Malformed ( _, _) => Err ( Error :: NonDecodable ( None ) ) ,
137+ // SAFETY: We allocate enough space above
138+ DecoderResult :: OutputFull => unreachable ! ( ) ,
139+ }
140+ }
141+
103142/// Automatic encoding detection of XML files based using the
104143/// [recommended algorithm](https://www.w3.org/TR/xml11/#sec-guessing).
105144///
0 commit comments