use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Store)]
pub fn store(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let output = quote! {
impl From<Vec<u8>> for #name {
fn from(v: Vec<u8>) -> Self {
Self::from(&v)
}
}
impl From<#name> for Vec<u8> {
fn from(v: #name) -> Vec<u8> {
Self::from(&v)
}
}
impl From<&#name> for Vec<u8> {
fn from(v: &#name) -> Vec<u8> {
let mut out:Vec<u8> = vec![];
revision::Revisioned::serialize_revisioned(v, &mut out).unwrap();
out
}
}
impl From<&Vec<u8>> for #name {
fn from(v: &Vec<u8>) -> Self {
revision::Revisioned::deserialize_revisioned(&mut v.as_slice()).unwrap()
}
}
};
output.into()
}
#[proc_macro_derive(Key)]
pub fn key(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let generics = input.generics;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
assert!(generics.lifetimes().count() <= 1);
let (lifetime, from_owned) = if let Some(lifetime_def) = generics.lifetimes().next() {
let lifetime = &lifetime_def.lifetime;
(quote! {#lifetime}, quote! {})
} else {
(
quote! {},
quote! {
impl #impl_generics From<Vec<u8>> for #name #ty_generics #where_clause {
fn from(v: Vec<u8>) -> Self {
Self::decode(&v).unwrap()
}
}
},
)
};
let output = quote! {
impl #impl_generics From<#name #ty_generics> for Vec<u8> #where_clause {
fn from(v: #name #ty_generics) -> Vec<u8> {
v.encode().unwrap_or_default()
}
}
impl #impl_generics From<&#name #ty_generics> for Vec<u8> #where_clause {
fn from(v: &#name #ty_generics) -> Vec<u8> {
v.encode().unwrap_or_default()
}
}
#from_owned
impl #impl_generics From<&#lifetime Vec<u8>> for #name #ty_generics #where_clause {
fn from(v: &#lifetime Vec<u8>) -> Self {
Self::decode(v).unwrap()
}
}
impl #impl_generics #name #ty_generics #where_clause {
pub fn encode(&self) -> Result<Vec<u8>, crate::err::Error> {
let v = storekey::serialize(self);
Ok(v?)
}
pub fn decode(v: &#lifetime[u8]) -> Result<Self, crate::err::Error> {
let v = storekey::deserialize(v);
Ok(v?)
}
}
};
output.into()
}