@@ -175,6 +175,7 @@ mod _pyexpat {
175175 } ,
176176 types:: Constructor ,
177177 } ;
178+ use alloc:: borrow:: Cow ;
178179 use alloc:: collections:: VecDeque ;
179180 use alloc:: rc:: Rc ;
180181 use core:: cell:: RefCell ;
@@ -220,6 +221,107 @@ mod _pyexpat {
220221
221222 type MutableObject = PyRwLock < PyObjectRef > ;
222223
224+ // Do not use Encoding::from_str here: xml-rs also accepts name prefixes.
225+ fn native_encoding ( name : & str ) -> Option < xml:: Encoding > {
226+ match name. to_ascii_uppercase ( ) . as_str ( ) {
227+ "UTF-8" => Some ( xml:: Encoding :: Utf8 ) ,
228+ "UTF-16" => Some ( xml:: Encoding :: Utf16 ) ,
229+ "UTF-16LE" => Some ( xml:: Encoding :: Utf16Le ) ,
230+ "UTF-16BE" => Some ( xml:: Encoding :: Utf16Be ) ,
231+ "ISO-8859-1" => Some ( xml:: Encoding :: Latin1 ) ,
232+ "US-ASCII" => Some ( xml:: Encoding :: Ascii ) ,
233+ _ => None ,
234+ }
235+ }
236+
237+ /// xml-rs emits StartDocument even without a declaration and fills in
238+ /// omitted values. Retain only the initial declaration to recover that
239+ /// information; the backend still validates it before any callback.
240+ #[ derive( Debug , Default ) ]
241+ struct DeclarationPrefix {
242+ bytes : Vec < u8 > ,
243+ complete : bool ,
244+ }
245+
246+ impl DeclarationPrefix {
247+ fn text ( & self ) -> String {
248+ let bytes = & self . bytes ;
249+ let ( little, offset) = if bytes. starts_with ( & [ 0xff , 0xfe ] ) {
250+ ( true , 2 )
251+ } else if bytes. starts_with ( & [ 0xfe , 0xff ] ) {
252+ ( false , 2 )
253+ } else if bytes. starts_with ( & [ b'<' , 0 ] ) {
254+ ( true , 0 )
255+ } else if bytes. starts_with ( & [ 0 , b'<' ] ) {
256+ ( false , 0 )
257+ } else {
258+ return String :: from_utf8_lossy (
259+ bytes. strip_prefix ( & [ 0xef , 0xbb , 0xbf ] ) . unwrap_or ( bytes) ,
260+ )
261+ . into_owned ( ) ;
262+ } ;
263+ let units = bytes[ offset..] . as_chunks :: < 2 > ( ) . 0 . iter ( ) . map ( |& pair| {
264+ if little {
265+ u16:: from_le_bytes ( pair)
266+ } else {
267+ u16:: from_be_bytes ( pair)
268+ }
269+ } ) ;
270+ char:: decode_utf16 ( units)
271+ . map ( |c| c. unwrap_or ( char:: REPLACEMENT_CHARACTER ) )
272+ . collect ( )
273+ }
274+
275+ fn record ( & mut self , chunk : & [ u8 ] ) {
276+ if self . complete {
277+ return ;
278+ }
279+ for & byte in chunk {
280+ self . bytes . push ( byte) ;
281+ if self . bytes . len ( ) >= 2
282+ && self . bytes . len ( ) <= 16
283+ && ![ 0xef , 0xbb , 0xbf ] . starts_with ( & self . bytes )
284+ {
285+ let text = self . text ( ) ;
286+ if ( !"<?xml" . starts_with ( & text) && !text. starts_with ( "<?xml" ) )
287+ || text. strip_prefix ( "<?xml" ) . is_some_and ( |tail| {
288+ !tail. is_empty ( ) && !tail. starts_with ( [ ' ' , '\t' , '\r' , '\n' ] )
289+ } )
290+ {
291+ self . bytes . clear ( ) ;
292+ self . complete = true ;
293+ break ;
294+ }
295+ }
296+ if self . bytes . ends_with ( b"?>" )
297+ || ( self . bytes . len ( ) . is_multiple_of ( 2 )
298+ && ( self . bytes . ends_with ( & [ b'?' , 0 , b'>' , 0 ] )
299+ || self . bytes . ends_with ( & [ 0 , b'?' , 0 , b'>' ] ) ) )
300+ {
301+ self . complete = true ;
302+ break ;
303+ }
304+ }
305+ }
306+
307+ fn take ( & mut self ) -> Option < String > {
308+ let text = self . text ( ) ;
309+ self . bytes . clear ( ) ;
310+ self . complete = true ;
311+ text. strip_prefix ( "<?xml" )
312+ . filter ( |tail| tail. starts_with ( [ ' ' , '\t' , '\r' , '\n' ] ) )
313+ . map ( str:: to_owned)
314+ }
315+ }
316+
317+ // Called only after xml-rs validated the declaration's attribute grammar.
318+ fn declaration_value < ' a > ( text : & ' a str , name : & str ) -> Option < & ' a str > {
319+ let ( _, value) = text. split_once ( name) ?;
320+ let value = value. trim_start ( ) . strip_prefix ( '=' ) ?. trim_start ( ) ;
321+ let quote = value. chars ( ) . next ( ) ?;
322+ value. get ( 1 ..) ?. split ( quote) . next ( )
323+ }
324+
223325 #[ pyattr( name = "version_info" ) ]
224326 pub ( super ) const VERSION_INFO : ( u32 , u32 , u32 ) = ( 2 , 7 , 1 ) ;
225327
@@ -238,6 +340,14 @@ mod _pyexpat {
238340 #[ pytraverse( skip) ]
239341 namespace_separator : Option < String > ,
240342 #[ pytraverse( skip) ]
343+ encoding : Option < String > ,
344+ #[ pytraverse( skip) ]
345+ declaration : PyRwLock < DeclarationPrefix > ,
346+ #[ pytraverse( skip) ]
347+ initial_bytes : PyRwLock < Vec < u8 > > ,
348+ #[ pytraverse( skip) ]
349+ input_unicode : PyRwLock < Option < bool > > ,
350+ #[ pytraverse( skip) ]
241351 base : PyRwLock < Option < String > > ,
242352 // Position of the last event produced, exposed as CurrentLineNumber /
243353 // CurrentColumnNumber / CurrentByteIndex (mirrors libexpat's
@@ -928,6 +1038,7 @@ mod _pyexpat {
9281038 #[ pyclass]
9291039 impl PyExpatLikeXmlParser {
9301040 fn new (
1041+ encoding : Option < String > ,
9311042 namespace_separator : Option < String > ,
9321043 intern : OptionalOption < PyObjectRef > ,
9331044 parent : Option < PyExpatLikeXmlParserRef > ,
@@ -940,6 +1051,10 @@ mod _pyexpat {
9401051 OptionalArg :: Present ( None ) => vm. ctx . none ( ) ,
9411052 } ;
9421053 Self {
1054+ encoding,
1055+ declaration : PyRwLock :: new ( DeclarationPrefix :: default ( ) ) ,
1056+ initial_bytes : PyRwLock :: new ( Vec :: new ( ) ) ,
1057+ input_unicode : PyRwLock :: new ( None ) ,
9431058 namespace_separator,
9441059 base : PyRwLock :: new ( None ) ,
9451060 current_line : PyRwLock :: new ( 1 ) ,
@@ -1128,10 +1243,24 @@ mod _pyexpat {
11281243 ) ;
11291244 }
11301245
1131- fn create_config ( & self , unicode_input : bool ) -> xml:: ParserConfig {
1246+ fn create_config (
1247+ & self ,
1248+ unicode_input : bool ,
1249+ sniffed : Option < xml:: Encoding > ,
1250+ ) -> xml:: ParserConfig {
1251+ let encoding = if unicode_input {
1252+ Some ( xml:: Encoding :: Utf8 )
1253+ } else {
1254+ self . encoding
1255+ . as_deref ( )
1256+ . and_then ( native_encoding)
1257+ . or ( sniffed)
1258+ } ;
11321259 xml:: ParserConfig :: new ( )
1133- . override_encoding ( unicode_input. then_some ( xml:: Encoding :: Utf8 ) )
1134- . ignore_invalid_encoding_declarations ( unicode_input)
1260+ . override_encoding ( encoding)
1261+ . ignore_invalid_encoding_declarations (
1262+ unicode_input || self . encoding . as_deref ( ) . and_then ( native_encoding) . is_some ( ) ,
1263+ )
11351264 . cdata_to_characters ( false )
11361265 . coalesce_characters ( false )
11371266 . ignore_comments ( false )
@@ -1195,6 +1324,7 @@ mod _pyexpat {
11951324 return Err ( vm. new_value_error ( "embedded null character" ) ) ;
11961325 }
11971326 let child = Self :: new (
1327+ encoding. clone ( ) ,
11981328 zelf. namespace_separator . clone ( ) ,
11991329 OptionalArg :: Present ( Some ( zelf. intern . clone ( ) ) ) ,
12001330 Some ( zelf. clone ( ) ) ,
@@ -1321,6 +1451,18 @@ mod _pyexpat {
13211451 XmlEvent :: StartDocument { standalone, .. } => {
13221452 self . standalone
13231453 . store ( standalone == Some ( true ) , Ordering :: Relaxed ) ;
1454+ let declaration = self . declaration . write ( ) . take ( ) ;
1455+ if let Some ( declaration) = declaration {
1456+ invoke_handler (
1457+ vm,
1458+ & self . xml_decl ,
1459+ (
1460+ declaration_value ( & declaration, "version" ) ,
1461+ declaration_value ( & declaration, "encoding" ) ,
1462+ standalone. map_or ( -1 , i32:: from) ,
1463+ ) ,
1464+ ) ?;
1465+ }
13241466 Ok ( ( ) )
13251467 }
13261468 XmlEvent :: Doctype { .. } => {
@@ -1824,17 +1966,34 @@ mod _pyexpat {
18241966 }
18251967 self . started . store ( true , Ordering :: Relaxed ) ;
18261968 self . check_completed ( vm) ?;
1969+ self . declaration . write ( ) . record ( chunk) ;
18271970 if self . finished . load ( Ordering :: SeqCst ) {
18281971 return Ok ( ( ) ) ;
18291972 }
1830- {
1831- let mut guard = self . backend . write ( ) ;
1832- if guard. is_none ( ) {
1833- // CPython selects UTF-8 for str input with XML_SetEncoding;
1834- // that call cannot change the encoding after parsing starts.
1835- * guard = Some ( Backend :: new ( self . create_config ( unicode_input) ) ) ;
1973+ let mut input = Cow :: Borrowed ( chunk) ;
1974+ if self . backend . read ( ) . is_none ( ) {
1975+ let unicode_input = * self . input_unicode . write ( ) . get_or_insert ( unicode_input) ;
1976+ // xml-rs detects a UTF-16 BOM, but unlike Expat does not
1977+ // recognize UTF-16 XML without one. Two initial bytes suffice
1978+ // to distinguish the endian form; retain only a split prefix.
1979+ let mut initial = self . initial_bytes . write ( ) ;
1980+ if !initial. is_empty ( ) {
1981+ initial. extend_from_slice ( chunk) ;
1982+ input = Cow :: Owned ( core:: mem:: take ( & mut * initial) ) ;
1983+ }
1984+ if !unicode_input && self . encoding . is_none ( ) && input. len ( ) < 2 && !isfinal {
1985+ initial. extend_from_slice ( & input) ;
1986+ return Ok ( ( ) ) ;
18361987 }
1988+ let sniffed = match input. as_ref ( ) {
1989+ [ 0 , _, ..] => Some ( xml:: Encoding :: Utf16Be ) ,
1990+ [ _, 0 , ..] => Some ( xml:: Encoding :: Utf16Le ) ,
1991+ _ => None ,
1992+ } ;
1993+ * self . backend . write ( ) =
1994+ Some ( Backend :: new ( self . create_config ( unicode_input, sniffed) ) ) ;
18371995 }
1996+ let chunk = input. as_ref ( ) ;
18381997 #[ cfg( not( target_arch = "wasm32" ) ) ]
18391998 {
18401999 let is_threaded = matches ! ( * self . backend. read( ) , Some ( Backend :: Threaded ( _) ) ) ;
@@ -1969,10 +2128,8 @@ mod _pyexpat {
19692128 return Err ( vm. new_type_error ( "intern must be a dictionary" ) ) ;
19702129 }
19712130
1972- // Encoding selection is still handled by the xml-rs backend.
1973- let _ = encoding;
1974-
19752131 Ok ( PyExpatLikeXmlParser :: new (
2132+ encoding. map ( |encoding| encoding. as_str ( ) . to_owned ( ) ) ,
19762133 ns_sep. map ( |sep| sep. as_str ( ) . to_owned ( ) ) ,
19772134 args. intern ,
19782135 None ,
0 commit comments