Skip to main content

mx20022_parse/
de.rs

1//! Deserialization of ISO 20022 XML messages.
2//!
3//! Thin wrappers around [`quick_xml::de`] that translate errors into
4//! [`ParseError`].
5//!
6//! # Examples
7//!
8//! ```no_run
9//! # use mx20022_parse::de::from_str;
10//! # use mx20022_model::generated::head::BusinessApplicationHeaderV04;
11//! let xml = r#"<AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.04">...</AppHdr>"#;
12//! let _hdr: BusinessApplicationHeaderV04 = from_str(xml).unwrap();
13//! ```
14
15use serde::de::DeserializeOwned;
16
17use crate::ParseError;
18
19/// Deserialize an ISO 20022 XML message from a string slice.
20///
21/// The root element name must match the serde rename of the target type.
22///
23/// # Errors
24///
25/// Returns [`ParseError::Deserialize`] if the XML is malformed or does not
26/// match the expected schema.
27pub fn from_str<T: DeserializeOwned>(xml: &str) -> Result<T, ParseError> {
28    quick_xml::de::from_str(xml).map_err(ParseError::Deserialize)
29}
30
31/// Deserialize an ISO 20022 XML message from a buffered reader.
32///
33/// # Errors
34///
35/// Returns [`ParseError::Deserialize`] if the XML is malformed or does not
36/// match the expected schema.
37pub fn from_reader<R: std::io::BufRead, T: DeserializeOwned>(reader: R) -> Result<T, ParseError> {
38    quick_xml::de::from_reader(reader).map_err(ParseError::Deserialize)
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    /// A struct that requires XML element structure to deserialize.
46    #[derive(serde::Deserialize, Debug)]
47    struct Foo {
48        #[allow(dead_code)]
49        x: u32,
50    }
51
52    #[test]
53    fn from_str_invalid_xml_returns_error() {
54        // "<<<garbage>>>" is invalid XML and cannot match the Foo struct shape.
55        let result: Result<Foo, _> = from_str("<<<garbage>>>");
56        assert!(result.is_err(), "malformed XML must return an error");
57    }
58
59    #[test]
60    fn from_reader_invalid_xml_returns_error() {
61        let xml = b"<<<garbage>>>";
62        let result: Result<Foo, _> = from_reader(xml.as_ref());
63        assert!(result.is_err(), "malformed XML must return an error");
64    }
65}