media-io / yaserde

Yet Another Serializer/Deserializer
MIT License
174 stars 58 forks source link

Fat enum not deserialized correctly #172

Open jwodder opened 6 months ago

jwodder commented 6 months ago

Running cargo test on the following code:

use yaserde_derive::YaDeserialize;

#[derive(Clone, Debug, Eq, PartialEq, YaDeserialize)]
#[yaserde(rename = "propfind", namespace = "DAV:")]
pub enum Propfind {
    PropName { propname: PropName },
    AllProp { allprop: AllProp },
}

// Just to shut yarserde up
impl Default for Propfind {
    fn default() -> Propfind {
        Propfind::AllProp { allprop: AllProp }
    }
}

impl Propfind {
    pub fn from_xml(s: &str) -> Result<Propfind, String> {
        yaserde::de::from_str(s)
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq, YaDeserialize)]
pub struct AllProp;

#[derive(Clone, Debug, Default, Eq, PartialEq, YaDeserialize)]
pub struct PropName;

#[cfg(test)]
mod tests {
    use super::*;
    use indoc::indoc;

    #[test]
    fn allprop() {
        let s = indoc! {r#"
            <?xml version="1.0" encoding="utf-8" ?>
            <propfind xmlns="DAV:">
                <allprop/>
            </propfind>
        "#};
        let pf = Propfind::from_xml(s).unwrap();
        assert_eq!(pf, Propfind::AllProp { allprop: AllProp });
    }

    #[test]
    fn propname() {
        let s = indoc! {r#"
            <?xml version="1.0" encoding="utf-8" ?>
            <propfind xmlns="DAV:">
                <propname/>
            </propfind>
        "#};
        let pf = Propfind::from_xml(s).unwrap();
        assert_eq!(pf, Propfind::PropName { propname: PropName });
    }
}

with the following dependencies:

[dependencies]
yaserde = "0.9.1"
yaserde_derive = "0.9.1"

[dev-dependencies]
indoc = "2.0.4"

results in the propname test failing because the XML is deserialized as Propfind::AllProp { allprop: AllProp } instead of the expected Propfind::PropName variant.

How can I get the given XML snippets to deserialize the way I want?

antis81 commented 1 month ago

Looks like this feature request also relates to what I was trying to achieve (example in #185). The approach is slightly different here, but the goal is practically identical. Often it is needed to keep the element order throughout the de-/serialization process.

Does #189 implement this actually?