Skip to main content

onehot_derive/
lib.rs

1/*!
2This crate provides a custom auto derive macro for [onehot](https://docs.rs/onehot/).
3*/
4
5mod attr;
6mod metadata;
7mod enums;
8mod structs;
9
10use proc_macro::TokenStream;
11use syn;
12
13
14/// The auto derive macro for OneHot.
15///
16/// Enums and structs:
17/// ```rust,ignore
18/// # use onehot::OneHot;
19/// #[derive(OneHot)]
20/// pub enum SimpleEnum {
21/// 	First,
22/// 	Second,
23/// 	#[onehot(ignore)] // Fields with the `ignore` attribute are disconsidered.
24/// 	Third,
25/// }
26///
27/// #[derive(OneHot)]
28/// struct SimpleStruct {
29/// 	f1: bool,
30/// 	f2: SimpleEnum,
31/// }
32/// ```
33///
34/// Structs can also be tuple and/or generic:
35/// ```rust,ignore
36/// # use onehot::OneHot;
37/// #[derive(OneHot)]
38/// pub struct SimpleGenericStruct<'a, T: OneHot + 'a>(
39/// 	bool,
40/// 	 &'a T,
41/// 	#[onehot(ignore)] u32
42/// );
43/// ```
44#[proc_macro_derive(OneHot, attributes(onehot))]
45pub fn onehot_derive(input: TokenStream) -> TokenStream {
46	let ast: syn::DeriveInput = syn::parse(input).unwrap();
47
48	let name = &ast.ident;
49
50	match ast.data {
51		syn::Data::Enum(ref _enum) => enums::impl_onehot(
52			name,
53			&_enum.variants,
54			ast.vis,
55			ast.generics,
56		),
57		syn::Data::Struct(ref _struct) => structs::impl_onehot(
58			name,
59			&_struct.fields,
60			ast.generics,
61		),
62		_ => panic!("OneHot can only be derived for structs and enums."),
63	}
64}