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 an extra function to provide the default value, as it is the case in
12/// serdes' implementation of default (`#[serde(default = "...")]`).
13///
14/// Set this macro on a struct where you use [`Serialize`] or [`Deserialize`] and use
15/// `#[serde_inline_default(...)]` on the field you want to have an inline default value.
16/// Replace the `...` with the value you want, and it will be set as default if serde needs it.
17///
18/// Note that you must set this macro _before_ `#[derive(Serialize)]` / `#[derive(Deserialize)]` as
19/// it won't work properly if it's set after the derive.
20///
21/// # Examples
22///
23/// ```rust
24/// #[serde_inline_default]
25/// #[derive(Deserialize)]
26/// struct Test {
27/// #[serde_inline_default(42)]
28/// value: u32
29/// }
30/// ```
31///
32/// [`Serialize`]: https://docs.rs/serde/*/serde/trait.Serialize.html
33/// [`Deserialize`]: https://docs.rs/serde/*/serde/trait.Deserialize.html
34#[proc_macro_attribute]
35pub fn serde_inline_default(_attr: TokenStream, input: TokenStream) -> TokenStream {
36 let item = parse_macro_input!(input as Item);
37
38 match item {
39 Item::Struct(s) => expand::expand_struct(s),
40 _ => panic!("can only be used on structs"),
41 }
42}