messagepack_derive/lib.rs
1#![deny(missing_docs)]
2
3//! Derive marco for [messagepack_core::encode::Encode] and [messagepack_core::decode::Decode]
4
5mod decode;
6mod encode;
7mod shared;
8
9use proc_macro::TokenStream;
10use syn::{DeriveInput, parse_macro_input};
11
12/// Derive the `Encode` trait for a struct.
13///
14/// # Supported types
15/// - **Named-field structs** — encoded as a MessagePack map by default
16/// - **Tuple structs** — encoded as a MessagePack array
17/// - **Unit structs** — encoded as MessagePack `nil`
18///
19/// # Container attributes
20/// - `#[msgpack(map)]` — encode as a MessagePack map (default for named-field structs)
21/// - `#[msgpack(array)]` — encode as a MessagePack array
22///
23/// # Field attributes
24/// - `#[msgpack(key = N)]` — required for all fields in `array` mode
25/// - `#[msgpack(bytes)]` — encode the field as MessagePack binary
26/// - `#[msgpack(encode_with = "path::to::fn")]` — custom encode function
27#[proc_macro_derive(Encode, attributes(msgpack))]
28pub fn derive_encode(input: TokenStream) -> TokenStream {
29 let input = parse_macro_input!(input as DeriveInput);
30 encode::derive_encode(input)
31 .unwrap_or_else(|e| e.to_compile_error())
32 .into()
33}
34
35/// Derive the `DecodeBorrowed` trait for a struct.
36///
37/// Named-field structs accept both map and array MessagePack formats on
38/// decode regardless of the `map`/`array` attribute.
39///
40/// # Supported types
41/// - **Named-field structs** — decoded from a MessagePack map or array
42/// - **Tuple structs** — decoded from a MessagePack array
43/// - **Unit structs** — decoded from MessagePack `nil`
44///
45/// # Container attributes
46/// - `#[msgpack(map)]` — default for named-field structs
47/// - `#[msgpack(array)]` — encode mode; requires `key` on every field
48///
49/// # Field attributes
50/// - `#[msgpack(key = N)]` — array index (required in `array` mode)
51/// - `#[msgpack(bytes)]` — decode the field from MessagePack binary
52/// - `#[msgpack(decode_with = "path::to::fn")]` — custom decode function
53#[proc_macro_derive(Decode, attributes(msgpack))]
54pub fn derive_decode(input: TokenStream) -> TokenStream {
55 let input = parse_macro_input!(input as DeriveInput);
56 decode::derive_decode(input)
57 .unwrap_or_else(|e| e.to_compile_error())
58 .into()
59}