use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use crate::{TypespaceTrait, TypespaceTraitSet};
#[derive(Debug, Clone, Copy)]
pub(crate) struct SerdeDerives {
serialize: bool,
deserialize: bool,
jsonschema: bool,
}
impl SerdeDerives {
pub(crate) fn new(traits: &TypespaceTraitSet) -> Self {
Self {
serialize: traits.contains(&TypespaceTrait::Serialize),
deserialize: traits.contains(&TypespaceTrait::Deserialize),
jsonschema: traits.contains(&TypespaceTrait::JsonSchema),
}
}
pub(crate) fn deserialize(self) -> bool {
self.deserialize
}
pub(crate) fn attrs(self) -> SerdeAttrs {
SerdeAttrs {
derives: self,
options: Vec::new(),
}
}
}
#[derive(Debug)]
pub(crate) struct SerdeAttrs {
derives: SerdeDerives,
options: Vec<TokenStream>,
}
impl SerdeAttrs {
pub(crate) fn push(&mut self, option: TokenStream) {
self.options.push(option);
}
}
impl Extend<TokenStream> for SerdeAttrs {
fn extend<T: IntoIterator<Item = TokenStream>>(&mut self, options: T) {
self.options.extend(options);
}
}
impl ToTokens for SerdeAttrs {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Self { derives, options } = self;
let serde = derives.serialize || derives.deserialize;
if !options.is_empty() {
if serde {
tokens.extend(quote! {
#[serde(
#( #options ),*
)]
});
} else if derives.jsonschema {
tokens.extend(quote! {
#[schemars(
#( #options ),*
)]
});
}
}
}
}