Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for mixed elements #185

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

antis81
Copy link

@antis81 antis81 commented May 25, 2024

Often it is required that the order of (XML) elements is unchanged. Since a Vec in Rust can only hold one type the idea is to wrap those alternatives by a Rust enum that dispatches to the actual YaSerde type (struct/enum/union).

This cannot be achieved with current struct/enum fields and YaSerialize/YaDeserialize proc_macros.

// Assuming ChildA/B are YaSerde structs
struct ChildA {}
struct ChildB {}

#[derive(yaserde_derive::YaDeserialize)
struct RootElem {
  a_children: Vec<ChildA>,  // this breaks the order…
  b_children: Vec<ChildB>,  // …of child elements
}

The example shows one idea to solve this by putting the ChildA/B structs inside a "dispatcher" enum.

#[derive(yaserde_derive::YaDeserialize)
struct RootElem {
  children: Vec<OneOfAorB>,  // elements are mixed w/o breaking the order
}

#[Default, YaDeserialize]  // <--- maybe YaDispatchedDeserialize and YaDispatchedSerialize (?)
// #[yaserde(dispatch)]   // <--- not supported currently (and most probably not a viable approach)
enum OneOfAorB {
  #[default]
  None,
  #[yaserde(rename = "a")]
  ChildA(ChildA),
  #[yaserde(rename = "b")]
  ChildB(ChildB),
}
impl YaSerializer for OneOfAorB {
  fn serialize(&self, /* … */) {
    match self {
      Self::None => (),
      Self::ChildA(a) => { a.serialize().unwrap(); }
      Self::ChildB(b) => { b.serialize().unwrap(); }
    }
  }
}

⚠️ Right now YaSerde doesn't support this.

Note that the meaning and behviour of the enum type in Rust highly differs from XML enum elements. The XML enum type does not support multiple occurences of the exact same type (-> tests/enum.rs shows this).

@antis81 antis81 changed the title Example for custom serializer based on YaSerialize trait Example for custom serializer to non-XML output Jun 13, 2024
@antis81 antis81 marked this pull request as ready for review June 13, 2024 19:48
@antis81 antis81 marked this pull request as draft June 14, 2024 11:31
@antis81 antis81 changed the title Example for custom serializer to non-XML output Support for mixed elements Jun 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant