relay_protocol_derive/
utils.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use proc_macro2::TokenStream;
use quote::ToTokens;
use synstructure::{Structure, VariantInfo};

pub trait SynstructureExt {
    fn try_each_variant<F, R>(&self, f: F) -> syn::Result<TokenStream>
    where
        F: FnMut(&VariantInfo<'_>) -> syn::Result<R>,
        R: ToTokens;
}

impl SynstructureExt for Structure<'_> {
    fn try_each_variant<F, R>(&self, mut f: F) -> syn::Result<TokenStream>
    where
        F: FnMut(&VariantInfo<'_>) -> syn::Result<R>,
        R: ToTokens,
    {
        let mut t = TokenStream::new();
        for variant in self.variants() {
            let pat = variant.pat();
            let body = f(variant)?;
            quote::quote!(#pat => { #body }).to_tokens(&mut t);
        }
        if self.omitted_variants() {
            quote::quote!(_ => {}).to_tokens(&mut t);
        }
        Ok(t)
    }
}