nuts_bytes_derive/lib.rs
1// MIT License
2//
3// Copyright (c) 2023 Robin Doer
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to
7// deal in the Software without restriction, including without limitation the
8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9// sell copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21// IN THE SOFTWARE.
22
23mod attr;
24mod from_bytes;
25mod to_bytes;
26
27use proc_macro::TokenStream;
28use quote::quote;
29use syn::{parse_macro_input, Data, DeriveInput};
30
31use crate::from_bytes::{from_bytes_enum, from_bytes_struct, from_bytes_union};
32use crate::to_bytes::{to_bytes_enum, to_bytes_struct, to_bytes_union};
33
34/// Derive macro implementation of the [`FromBytes`] trait.
35///
36/// This derive macro generates a [`FromBytes`] implementation for `struct` and
37/// `enum` types. `union` types are currently not supported.
38///
39/// # Attributes
40///
41/// * **`#[nuts_bytes(map_from_bytes = $path)]`**
42///
43/// Calls the function `$path` on the deserialized value.
44/// The given function must be callable as
45/// `fn<S: FromBytes, T, E: Into<Box<dyn std::error::Error + Send + Sync>>(S) -> std::result::Result<T, E>`
46///
47/// If the function succeeds, the returned value is assigned to this field. An
48/// error is converted into a [`Error::Custom`] error, where the error (`E`) is
49/// attached to the [`Error::Custom`] variant.
50///
51/// * **`#[nuts_bytes(map = $module)]`**
52///
53/// Combination of `map_from_bytes` and `map_to_bytes`. The crate will use
54/// `$module::from_bytes` as the `map_from_bytes` function and
55/// `$module::to_bytes` as the `map_to_bytes` function.
56///
57/// [`FromBytes`]: trait.FromBytes.html
58/// [`Error::Custom`]: enum.Error.html#variant.Custom
59#[proc_macro_derive(FromBytes, attributes(nuts_bytes))]
60pub fn from_bytes(input: TokenStream) -> TokenStream {
61 let input = parse_macro_input!(input as DeriveInput);
62
63 let name = input.ident;
64 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
65
66 let from_impl = match input.data {
67 Data::Struct(data) => from_bytes_struct(&name, data),
68 Data::Enum(data) => from_bytes_enum(&name, data),
69 Data::Union(_data) => from_bytes_union(&name),
70 };
71
72 let expanded = quote! {
73 impl #impl_generics nuts_bytes::FromBytes for #name #ty_generics #where_clause {
74 fn from_bytes<TB: nuts_bytes::TakeBytes>(source: &mut TB) -> std::result::Result<Self, nuts_bytes::Error> {
75 let result = { #from_impl };
76
77 Ok(result)
78 }
79 }
80 };
81
82 TokenStream::from(expanded)
83}
84
85/// Derive macro implementation of the [`ToBytes`] trait.
86///
87/// This derive macro generates a [`ToBytes`] implementation for `struct` and
88/// `enum` types. `union` types are currently not supported.
89///
90/// [`ToBytes`]: trait.ToBytes.html
91#[proc_macro_derive(ToBytes, attributes(nuts_bytes))]
92pub fn to_bytes(input: TokenStream) -> TokenStream {
93 let input = parse_macro_input!(input as DeriveInput);
94
95 let name = input.ident;
96 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
97
98 let to_impl = match input.data {
99 Data::Struct(data) => to_bytes_struct(&name, data),
100 Data::Enum(data) => to_bytes_enum(&name, data),
101 Data::Union(_data) => to_bytes_union(&name),
102 };
103
104 let expanded = quote! {
105 impl #impl_generics nuts_bytes::ToBytes for #name #ty_generics #where_clause {
106 fn to_bytes<PB: nuts_bytes::PutBytes>(&self, target: &mut PB) -> std::result::Result<usize, nuts_bytes::Error> {
107 #to_impl
108 }
109 }
110 };
111
112 TokenStream::from(expanded)
113}