serde_inline_default/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use proc_macro::TokenStream;
4use syn::{parse_macro_input, Item};
5
6mod expand;
7mod utils;
8
9/// The main macro of this crate.
10/// Use it to define default values of fields in structs you [`Serialize`] or [`Deserialize`].
11/// You do not need to create a extra function to provide the default value, as it is the case in serdes' implementation of default (`#[serde(default = "...")]`).
12///
13/// Set this macro on a struct where you use [`Serialize`] or [`Deserialize`] and use `#[serde_inline_default(...)]` on the field you want to have a inline default value.
14/// Replace the `...` with the value you want and it will be set as default if serde needs it.
15///
16/// Note that you must set this macro _before_ `#[derive(Serialize)]` / `#[derive(Deserialize)]` as it wouldn't work properly if set after the derive.
17///
18/// # Examples
19///
20/// ```rust
21/// #[serde_inline_default]
22/// #[derive(Deserialize)]
23/// struct Test {
24///     #[serde_inline_default(42)]
25///     value: u32
26/// }
27/// ```
28///
29/// [`Serialize`]: https://docs.rs/serde/*/serde/trait.Serialize.html
30/// [`Deserialize`]: https://docs.rs/serde/*/serde/trait.Deserialize.html
31#[proc_macro_attribute]
32pub fn serde_inline_default(_attr: TokenStream, input: TokenStream) -> TokenStream {
33    let item = parse_macro_input!(input as Item);
34
35    match item {
36        Item::Struct(s) => expand::expand_struct(s),
37        _ => panic!("can only be used on structs"),
38    }
39}