Skip to content

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