serde_struct_tuple/
lib.rs

1//! # serde-struct-tuple
2//!
3//! **serde-struct-tuple** is a utility crate, built initially for [`battler-wamp`](https://crates.io/crates/battler-wamp). It provides procedural macros to automatically derive [`serde`](https://serde.rs/)'s `Serialize` and `Deserialize` traits for struct types that should be encoded as a tuple (list) of its fields.
4//!
5//! Struct fields can be any type that implement `serde::Serialize` and/or `serde::Deserialize`.
6//!
7//! The macro also has additional optional attributes for struct fields:
8//!
9//! * `default` - If the field is missing during deserialization, the field is initialized to its
10//!   default value.
11//! * `skip_serializing_if` - Checks if the field should be skipped during serialization using the
12//!   function provided. All subsequent fields will also be skipped, regardless of their value.
13//!
14//! ## Example
15//!
16//! ```
17//! use std::collections::BTreeMap;
18//!
19//! use serde_struct_tuple::{
20//!     DeserializeStructTuple,
21//!     SerializeStructTuple,
22//! };
23//!
24//! fn is_true(b: &bool) -> bool {
25//!     *b
26//! }
27//!
28//! #[derive(Debug, Default, PartialEq, Eq, SerializeStructTuple, DeserializeStructTuple)]
29//! struct Message {
30//!     a: u64,
31//!     b: String,
32//!     #[serde_struct_tuple(default, skip_serializing_if = Vec::is_empty)]
33//!     c: Vec<u64>,
34//!     #[serde_struct_tuple(default, skip_serializing_if = BTreeMap::is_empty)]
35//!     d: BTreeMap<u8, bool>,
36//!     #[serde_struct_tuple(default, skip_serializing_if = is_true)]
37//!     e: bool,
38//! }
39//!
40//! fn main() {
41//!     // Serialization.
42//!     assert_eq!(
43//!         serde_json::to_string(&Message {
44//!             a: 123,
45//!             b: "foo".to_owned(),
46//!             e: true,
47//!             ..Default::default()
48//!         })
49//!         .unwrap(),
50//!         r#"[123,"foo"]"#
51//!     );
52//!     assert_eq!(
53//!         serde_json::to_string(&Message {
54//!             a: 123,
55//!             b: "foo".to_owned(),
56//!             d: BTreeMap::from_iter([(1, false), (2, true)]),
57//!             e: true,
58//!             ..Default::default()
59//!         })
60//!         .unwrap(),
61//!         r#"[123,"foo",[],{"1":false,"2":true}]"#
62//!     );
63//!     assert_eq!(
64//!         serde_json::to_string(&Message {
65//!             a: 123,
66//!             b: "foo".to_owned(),
67//!             c: Vec::from_iter([6, 7, 8]),
68//!             d: BTreeMap::from_iter([(1, false), (2, true)]),
69//!             ..Default::default()
70//!         })
71//!         .unwrap(),
72//!         r#"[123,"foo",[6,7,8],{"1":false,"2":true},false]"#
73//!     );
74//!
75//!     // Deserialization.
76//!     assert_eq!(
77//!         serde_json::from_str::<Message>(r#"[123, "foo"]"#).unwrap(),
78//!         Message {
79//!             a: 123,
80//!             b: "foo".to_owned(),
81//!             ..Default::default()
82//!         }
83//!     );
84//!     assert_eq!(
85//!         serde_json::from_str::<Message>(r#"[123, "foo", [99, 100], { "20": true }, true]"#)
86//!             .unwrap(),
87//!         Message {
88//!             a: 123,
89//!             b: "foo".to_owned(),
90//!             c: Vec::from_iter([99, 100]),
91//!             d: BTreeMap::from_iter([(20, true)]),
92//!             e: true,
93//!         }
94//!     );
95//! }
96//! ```
97
98pub use serde_struct_tuple_proc_macro::{
99    DeserializeStructTuple,
100    SerializeStructTuple,
101};
102
103/// Trait for deserializing a struct from a tuple of its fields.
104pub trait DeserializeStructTuple {
105    type Value;
106
107    /// The [`serde::de::Visitor`] implementation that reads all fields from a sequence into the
108    /// struct.
109    fn visitor<'de>() -> impl serde::de::Visitor<'de, Value = Self::Value>;
110}
111
112/// Trait for serializing a struct into a tuple of its fields.
113pub trait SerializeStructTuple {
114    /// Serializes all struct fields to the given [`serde::ser::SerializeSeq`], in declaration
115    /// order.
116    fn serialize_fields_to_seq<S>(&self, seq: &mut S) -> core::result::Result<(), S::Error>
117    where
118        S: serde::ser::SerializeSeq;
119}