messagepack_rs_macros/
lib.rs1#![forbid(unsafe_code)]
2
3extern crate proc_macro;
4
5use crate::proc_macro::TokenStream;
6use quote::quote;
7use syn;
8
9#[proc_macro_derive(MessagePackFrom)]
10pub fn message_pack_from_macro_derive(input: TokenStream) -> TokenStream {
11 let ast = syn::parse(input).unwrap();
12 impl_message_pack_from_macro(&ast)
13}
14
15fn impl_message_pack_from_macro(ast: &syn::DeriveInput) -> TokenStream {
16 let name = &ast.ident;
17 let gen = quote! {
18 impl<T: Into<#name>> From<Option<T>> for #name {
19 fn from(value: Option<T>) -> Self {
20 value.map_or(Self::Nil, Into::into)
21 }
22 }
23
24 impl From<bool> for #name {
25 fn from(value: bool) -> Self {
26 Self::Bool(value)
27 }
28 }
29
30 impl From<f32> for #name {
31 fn from(value: f32) -> Self {
32 Self::Float32(value)
33 }
34 }
35
36 impl From<f64> for #name {
37 fn from(value: f64) -> Self {
38 Self::Float64(value)
39 }
40 }
41
42 impl From<u8> for #name {
43 fn from(value: u8) -> Self {
44 Self::UInt8(value)
45 }
46 }
47
48 impl From<u16> for #name {
49 fn from(value: u16) -> Self {
50 Self::UInt16(value)
51 }
52 }
53
54 impl From<u32> for #name {
55 fn from(value: u32) -> Self {
56 Self::UInt32(value)
57 }
58 }
59
60 impl From<u64> for #name {
61 fn from(value: u64) -> Self {
62 Self::UInt64(value)
63 }
64 }
65
66 impl From<i8> for #name {
67 fn from(value: i8) -> Self {
68 Self::Int8(value)
69 }
70 }
71
72 impl From<i16> for #name {
73 fn from(value: i16) -> Self {
74 Self::Int16(value)
75 }
76 }
77
78 impl From<i32> for #name {
79 fn from(value: i32) -> Self {
80 Self::Int32(value)
81 }
82 }
83
84 impl From<i64> for #name {
85 fn from(value: i64) -> Self {
86 Self::Int64(value)
87 }
88 }
89
90 impl From<String> for #name {
91 fn from(value: String) -> Self {
92 Self::String(value)
93 }
94 }
95
96 impl From<Binary> for #name {
97 fn from(value: Binary) -> Self {
98 Self::Binary(value)
99 }
100 }
101
102 impl From<&str> for #name {
103 fn from(value: &str) -> Self {
104 Self::String(String::from(value))
105 }
106 }
107
108 impl From<Vec<Self>> for #name {
109 fn from(value: Vec<Self>) -> Self {
110 Self::Array(value)
111 }
112 }
113
114 impl From<&[Self]> for #name {
115 fn from(value: &[Self]) -> Self {
116 Self::Array(Vec::from(value))
117 }
118 }
119
120 impl From<BTreeMap<String, Self>> for #name {
121 fn from(value: BTreeMap<String, Self>) -> Self {
122 Self::Map(value)
123 }
124 }
125
126 impl From<Extension> for #name {
127 fn from(value: Extension) -> Self {
128 Self::Extension(value)
129 }
130 }
131
132 impl From<DateTime<Utc>> for #name {
133 fn from(value: DateTime<Utc>) -> Self {
134 Self::Timestamp(value)
135 }
136 }
137 };
138 gen.into()
139}