Macro - create a wrapper struct based on a enum name

I have create a macro which create a Serializer and Deserialize for a Set of Enum Fields. To do this i create a wrap struct. Now i use a fix name "Warp". But i want to use a name like SetOf(enum name) How do i do this.

Rust Playground

use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::ser::{Serialize, SerializeStruct, Serializer};
use serde_derive::*;
use std::collections::BTreeSet;
use std::fmt;
use failure::Error;

fn main() -> Result<(), Error> {
    let mut t = BTreeSet::new();
    t.insert(FieldType::A(34));
    t.insert(FieldType::F(true));

    let tt = Wrap(t);
    println!("in {:?}", tt);
    let s = serde_json::to_string(&tt)?;
    println!("to json '{}'", s);
    let ttt: Wrap = serde_json::from_str(&s)?;
    println!("from json {:?}", ttt);


    // let bson = bson::to_bson(&t);
    // println!("Encoded bson: {:?}", bson);
    // let result: Wrap = bson::from_bson(bson?)?;
    // println!("Decode: bson {:?}", result);
    // assert_eq!(result, *msg);

    Ok(())
}

macro_rules! tagged_enum {
    ($name:ident { $( $variant:ident ( $content:ty ), )* }) => {
        #[derive(Debug, Eq, PartialEq, Hash, Clone, Serialize, Deserialize, PartialOrd, Ord)]
        enum $name {
            $(
                $variant($content),
            )*
        }

        #[derive(Debug, Eq, PartialEq, Hash, Clone, PartialOrd, Ord)]
        struct Wrap(BTreeSet<$name>);

        impl Serialize for Wrap {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                let mut state = serializer.serialize_struct(stringify!($name), self.0.len())?;
                for e in &self.0 {
                    match e {
                        $(
                             $name::$variant(v) => state.serialize_field(stringify!($variant), &v)?,
                        )*
                    }
                }
                state.end()
            }
        }

The only way to mess with identifiers like that is with a procedural macro. If you don't want to write a procedural macro, there is the mashup crate which provides a wrapper around this functionality that you can use in a regular macro (though it's a bit tricky to figure out how to use it at first!).

Thanks, mashup brought me to the paste crate that can do what I needed.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.