From 7074344834d74dc0992e575433b641292880809e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Sch=C3=A4fer?= Date: Tue, 17 Dec 2024 19:31:29 +0100 Subject: [PATCH] xso: correctly handle I/O errors during start event in from_reader Without this, it'd panic, which is "not ideal", as they say. --- xso/src/lib.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/xso/src/lib.rs b/xso/src/lib.rs index a96ba854..5939b6cd 100644 --- a/xso/src/lib.rs +++ b/xso/src/lib.rs @@ -493,11 +493,33 @@ pub fn from_bytes(mut buf: &[u8]) -> Result { Err(self::error::Error::XmlError(rxml::Error::InvalidEof(None))) } +fn read_start_event_io( + r: &mut rxml::Reader, +) -> io::Result<(rxml::QName, rxml::AttrMap)> { + for ev in r { + match ev? { + rxml::Event::XmlDeclaration(_, rxml::XmlVersion::V1_0) => (), + rxml::Event::StartElement(_, name, attrs) => return Ok((name, attrs)), + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + self::error::Error::Other("Unexpected event at start of document"), + )) + } + } + } + Err(io::Error::new( + io::ErrorKind::InvalidData, + self::error::Error::XmlError(rxml::Error::InvalidEof(Some( + rxml::error::ErrorContext::DocumentBegin, + ))), + )) +} + /// Attempt to parse a type implementing [`FromXml`] from a reader. pub fn from_reader(r: R) -> io::Result { let mut reader = rxml::Reader::new(r); - let (name, attrs) = - read_start_event(&mut reader).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let (name, attrs) = read_start_event_io(&mut reader)?; let mut builder = match T::from_events(name, attrs) { Ok(v) => v, Err(self::error::FromEventsError::Mismatch { .. }) => {