Skip to main content

atm0s_media_server_proc_macro/
lib.rs

1extern crate proc_macro;
2
3use proc_macro::TokenStream;
4use quote::quote;
5use syn::{parse_macro_input, DeriveInput};
6
7#[proc_macro_derive(IntoVecU8)]
8pub fn into_vec_u8_derive(input: TokenStream) -> TokenStream {
9    // Parse the input tokens into a syntax tree
10    let input = parse_macro_input!(input as DeriveInput);
11
12    // Used to get the name of the struct
13    let name = input.ident;
14
15    // The expanded code
16    let expanded = quote! {
17        impl Into<Vec<u8>> for #name {
18            fn into(self) -> Vec<u8> {
19                bincode::serialize(&self).expect("Should convert to VecU8 by bincode")
20            }
21        }
22    };
23
24    // Return the generated impl as a TokenStream
25    TokenStream::from(expanded)
26}
27
28#[proc_macro_derive(TryFromSliceU8)]
29pub fn from_slice_u8_derive(input: TokenStream) -> TokenStream {
30    // Parse the input tokens into a syntax tree
31    let input = parse_macro_input!(input as DeriveInput);
32
33    // Used to get the name of the struct
34    let name = input.ident;
35
36    // The expanded code
37    let expanded = quote! {
38        impl TryFrom<&[u8]> for #name {
39            type Error = ();
40
41            fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
42                bincode::deserialize(value).map_err(|_| ())
43            }
44        }
45    };
46
47    // Return the generated impl as a TokenStream
48    TokenStream::from(expanded)
49}