bincode_next/features/serde/mod.rs
1//! Support for serde integration. Enable this with the `serde` feature.
2//!
3//! To encode/decode type that implement serde's trait, you can use:
4//! - [`borrow_decode_from_slice`\]
5//! - [`decode_from_slice`\]
6//! - [`encode_into_slice`\]
7//! - [`encode_to_vec`\]
8//!
9//! For interop with bincode's [Decode]/[Encode], you can use:
10//! - [`Compat`\]
11//! - [`BorrowCompat`\]
12//!
13//! For interop with bincode's `derive` feature, you can use the `#[bincode(with_serde)]` attribute on each field that implements serde's traits.
14//!
15//! ```
16//! # #[cfg(feature = "derive")]
17//! # mod foo {
18//! # use bincode_next::{Decode, Encode};
19//! # use serde_derive::{Deserialize, Serialize};
20//! #[derive(Serialize, Deserialize)]
21//! pub struct SerdeType {
22//! // ...
23//! }
24//!
25//! #[derive(Decode, Encode)]
26//! pub struct StructWithSerde {
27//! #[bincode(with_serde)]
28//! pub serde: SerdeType,
29//! }
30//!
31//! #[derive(Decode, Encode)]
32//! pub enum EnumWithSerde {
33//! Unit(#[bincode(with_serde)] SerdeType),
34//! Struct {
35//! #[bincode(with_serde)]
36//! serde: SerdeType,
37//! },
38//! }
39//! # }
40//! ```
41//!
42//! # Known issues
43//!
44//! Because bincode is a format without meta data, there are several known issues with serde's attributes. Please do not use any of the following attributes if you plan on using bincode, or use bincode's own `derive` macros.
45//! - `#[serde(flatten)]`
46//! - `#[serde(skip)]`
47//! - `#[serde(skip_deserializing)]`
48//! - `#[serde(skip_serializing)]`
49//! - `#[serde(skip_serializing_if = "path")]`
50//! - `#[serde(tag = "...")]`
51//! - `#[serde(untagged)]`
52//!
53//! **Using any of the above attributes can and will cause issues with bincode and will result in lost data**. Consider using bincode's own derive macro instead.
54//!
55//! Missing trailing struct fields return `UnexpectedEnd`, even with `#[serde(default)]`.
56//! Bincode does not encode field names or struct field counts, so it cannot distinguish missing
57//! fields from truncated input. Use explicit schema versioning to decode older struct layouts.
58//!
59//! ### `deserialize_any` and Self-Describing Formats
60//!
61//! Bincode is not a self-describing format (it does not store type metadata with the data map like JSON does). Because of this, it **does not support `deserialize_any`**.
62//!
63//! This means that types like `serde_json::Value` or `toml::Value` cannot be deserialized directly from a bincode stream. Attempting to do so will result in an `AnyNotSupported` error. To work around this, you must deserialize into strongly-typed data structures representing your schema, rather than dynamic or nested value enums.
64//!
65//! # Why move away from serde?
66//!
67//! Serde is a great library, but it has some issues that makes us want to be decoupled from serde:
68//! - The issues documented above with attributes.
69//! - Serde has chosen to not have a MSRV ([source](https://github.com/serde-rs/serde/pull/2257)). We think MSRV is important, bincode 1 still compiles with rust 1.18.
70//! - Before serde we had rustc-serializer. Serde has more than replaced rustc-serializer, but we can imagine a future where serde is replaced by something else.
71//! - We believe that less dependencies is better, and that you should be able to choose your own dependencies. If you disable all features, bincode 2 only has 1 dependency. ([`unty`\], a micro crate we manage ourselves)
72//!
73//! **note:** just because we're making serde an optional dependency, it does not mean we're dropping support for serde. Serde will still be fully supported, we're just giving you the option to not use it.
74//!
75//! [Decode]: ../de/trait.Decode.html
76//! [Encode]: ../enc/trait.Encode.html
77//! [`unty`\]: <https://crates.io/crates/unty>
78
79mod de_borrowed;
80mod de_owned;
81mod ser;
82
83pub use self::de_borrowed::*;
84pub use self::de_owned::*;
85pub use self::ser::*;
86
87use serde::de::Visitor;
88
89#[cfg(feature = "async-fiber")]
90#[doc(alias = "decode_serde_async")]
91#[doc(inline)]
92pub use crate::decode_serde_async as decode_async;
93#[cfg(feature = "async-fiber")]
94#[doc(alias = "decode_serde_async_with_context")]
95#[doc(inline)]
96pub use crate::decode_serde_async_with_context as decode_async_with_context;
97#[cfg(all(feature = "tokio", feature = "async-fiber", feature = "serde"))]
98#[doc(alias = "decode_serde_async_tokio")]
99#[doc(inline)]
100pub use crate::decode_serde_tokio_async as decode_async_tokio;
101#[cfg(all(feature = "tokio", feature = "async-fiber", feature = "serde"))]
102#[doc(alias = "decode_serde_async_tokio_with_context")]
103#[doc(inline)]
104pub use crate::decode_serde_tokio_async_with_context as decode_async_tokio_with_context;
105
106#[doc(hidden)]
107#[macro_export]
108#[rustfmt::skip]
109macro_rules! bincode_error_serde {
110 (
111 $(#[$meta:meta])*
112 $vis:vis enum $name:ident {
113 $(
114 $(#[$variant_meta:meta])*
115 $variant:ident $( { $( $(#[$field_meta:meta])* $field:ident : $ftype:ty ),* $(,)? } )? $( ( $( $(#[$tuple_meta:meta])* $tname:ident : $ttype:ty ),* $(,)? ) )?
116 ),* $(,)?
117 }
118 ) => {
119 $(#[$meta])*
120 $vis enum $name {
121 $(
122 $(#[$variant_meta])*
123 $variant $( { $( $(#[$field_meta])* $field : $ftype ),* } )? $( ( $( $(#[$tuple_meta])* $ttype ),* ) )?,
124 )*
125 }
126
127 pastey::paste! {
128 $(
129 $(#[$variant_meta])*
130 #[doc(hidden)]
131 #[cold]
132 #[track_caller]
133 #[inline(never)]
134 pub const fn [<cold_ $name:snake _ $variant:snake>]<'de, V>(
135 $($($field : $ftype),*)?
136 $($($tname : $ttype),*)?
137 ) -> core::result::Result<<V as Visitor<'de>>::Value, $name>
138 where
139 V: Visitor<'de>,
140 {
141 core::result::Result::Err($name::$variant $( { $($field),* } )? $( ( $( $tname ),* ) )?)
142 }
143 )*
144 }
145 };
146}
147
148bincode_error_serde! {
149 /// A serde-specific error that occurred while decoding.
150 #[derive(Debug)]
151 #[non_exhaustive]
152 pub enum DecodeError {
153 /// Bincode does not support serde's `any` decoding feature.
154 ///
155 /// See the "known issues" list in the serde module for more information on this.
156 AnyNotSupported,
157
158 /// Bincode does not support serde identifiers
159 IdentifierNotSupported,
160
161 /// Bincode does not support serde's `ignored_any`.
162 ///
163 /// See the "known issues" list in the serde module for more information on this.
164 IgnoredAnyNotSupported,
165
166 /// Serde tried decoding a borrowed value from an owned reader. Use `serde_decode_borrowed_from_*` instead
167 CannotBorrowOwnedData,
168
169 /// Could not allocate data like `String` and `Vec<u8>`
170 #[cfg(not(feature = "alloc"))]
171 CannotAllocate,
172
173 /// Custom serde error but bincode is unable to allocate a string. Set a breakpoint where this is thrown for more information.
174 #[cfg(not(feature = "alloc"))]
175 CustomError,
176 }
177}
178
179#[cfg(feature = "alloc")]
180impl serde::de::Error for crate::error::DecodeError {
181 fn custom<T>(msg: T) -> Self
182 where
183 T: core::fmt::Display,
184 {
185 use alloc::string::ToString;
186 crate::error::cold_decode_error_other_string::<()>(msg.to_string()).unwrap_err()
187 }
188}
189
190#[cfg(not(feature = "alloc"))]
191impl serde::de::Error for crate::error::DecodeError {
192 fn custom<T>(_: T) -> Self
193 where
194 T: core::fmt::Display,
195 {
196 crate::error::cold_decode_error_serde::<()>(DecodeError::CustomError).unwrap_err()
197 }
198}
199
200/// A serde-specific error that occurred while encoding.
201#[derive(Debug)]
202#[non_exhaustive]
203pub enum EncodeError {
204 /// Serde provided bincode with a sequence without a length, which is not supported in bincode
205 SequenceMustHaveLength,
206
207 /// [Serializer::collect_str] got called but bincode was unable to allocate memory.
208 #[cfg(not(feature = "alloc"))]
209 CannotCollectStr,
210
211 /// Custom serde error but bincode is unable to allocate a string. Set a breakpoint where this is thrown for more information.
212 #[cfg(not(feature = "alloc"))]
213 CustomError,
214}
215
216#[allow(clippy::from_over_into)]
217impl Into<crate::error::EncodeError> for EncodeError {
218 fn into(self) -> crate::error::EncodeError {
219 crate::error::cold_encode_error_serde::<()>(self).unwrap_err()
220 }
221}
222
223#[cfg(feature = "alloc")]
224impl serde::ser::Error for crate::error::EncodeError {
225 fn custom<T>(msg: T) -> Self
226 where
227 T: core::fmt::Display,
228 {
229 use alloc::string::ToString;
230
231 crate::error::cold_encode_error_other_string::<()>(msg.to_string()).unwrap_err()
232 }
233}
234
235#[cfg(not(feature = "alloc"))]
236impl serde::ser::Error for crate::error::EncodeError {
237 fn custom<T>(_: T) -> Self
238 where
239 T: core::fmt::Display,
240 {
241 crate::error::cold_encode_error_serde::<()>(EncodeError::CustomError).unwrap_err()
242 }
243}
244
245/// Wrapper struct that implements [`crate::Decode`\] and [`crate::Encode`\] on any type that implements serde's [`DeserializeOwned`\] and [`Serialize`\] respectively.
246///
247/// This works for most types, but if you're dealing with borrowed data consider using [`BorrowCompat`\] instead.
248///
249/// [Decode]: ../de/trait.Decode.html
250/// [Encode]: ../enc/trait.Encode.html
251/// [DeserializeOwned]: https://docs.rs/serde/1/serde/de/trait.DeserializeOwned.html
252/// [Serialize]: https://docs.rs/serde/1/serde/trait.Serialize.html
253#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
254pub struct Compat<T>(pub T);
255
256impl<Context, T> crate::Decode<Context> for Compat<T>
257where
258 T: serde::de::DeserializeOwned,
259{
260 fn decode<D: crate::de::Decoder>(decoder: &mut D) -> Result<Self, crate::error::DecodeError> {
261 let serde_decoder = de_owned::SerdeDecoder { de: decoder };
262 T::deserialize(serde_decoder).map(Compat)
263 }
264}
265impl<'de, T, Context> crate::BorrowDecode<'de, Context> for Compat<T>
266where
267 T: serde::de::DeserializeOwned,
268{
269 fn borrow_decode<D: crate::de::BorrowDecoder<'de>>(
270 decoder: &mut D
271 ) -> Result<Self, crate::error::DecodeError> {
272 let serde_decoder = de_owned::SerdeDecoder { de: decoder };
273 T::deserialize(serde_decoder).map(Compat)
274 }
275}
276
277impl<T> crate::Encode for Compat<T>
278where
279 T: serde::Serialize,
280{
281 fn encode<E: crate::enc::Encoder>(
282 &self,
283 encoder: &mut E,
284 ) -> Result<(), crate::error::EncodeError> {
285 let serializer = ser::SerdeEncoder { enc: encoder };
286 self.0.serialize(serializer)?;
287 Ok(())
288 }
289}
290
291impl<T> core::fmt::Debug for Compat<T>
292where
293 T: core::fmt::Debug,
294{
295 fn fmt(
296 &self,
297 f: &mut core::fmt::Formatter<'_>,
298 ) -> core::fmt::Result {
299 f.debug_tuple("Compat").field(&self.0).finish()
300 }
301}
302
303impl<T> core::fmt::Display for Compat<T>
304where
305 T: core::fmt::Display,
306{
307 fn fmt(
308 &self,
309 f: &mut core::fmt::Formatter<'_>,
310 ) -> core::fmt::Result {
311 self.0.fmt(f)
312 }
313}
314
315/// Wrapper struct that implements [`crate::de::BorrowDecode`\] and [`crate::Encode`\] on any type that implements serde's [`Deserialize`\] and [`Serialize`\] respectively.
316///
317/// This is mostly used on `&[u8]` and `&str`, for other types consider using [`Compat`\] instead.
318/// [`Deserialize`\]: <https://docs.rs/serde/1/serde/de/trait.Deserialize.html>
319/// [`Serialize`\]: <https://docs.rs/serde/1/serde/trait.Serialize.html>
320#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
321pub struct BorrowCompat<T>(pub T);
322
323impl<'de, T, Context> crate::de::BorrowDecode<'de, Context> for BorrowCompat<T>
324where
325 T: serde::de::Deserialize<'de>,
326{
327 fn borrow_decode<D: crate::de::BorrowDecoder<'de>>(
328 decoder: &mut D
329 ) -> Result<Self, crate::error::DecodeError> {
330 let serde_decoder = de_borrowed::SerdeDecoder {
331 de: decoder,
332 pd: core::marker::PhantomData,
333 };
334 T::deserialize(serde_decoder).map(BorrowCompat)
335 }
336}
337
338impl<T> crate::Encode for BorrowCompat<T>
339where
340 T: serde::Serialize,
341{
342 fn encode<E: crate::enc::Encoder>(
343 &self,
344 encoder: &mut E,
345 ) -> Result<(), crate::error::EncodeError> {
346 let serializer = ser::SerdeEncoder { enc: encoder };
347 self.0.serialize(serializer)?;
348 Ok(())
349 }
350}
351
352impl<T> core::fmt::Debug for BorrowCompat<T>
353where
354 T: core::fmt::Debug,
355{
356 fn fmt(
357 &self,
358 f: &mut core::fmt::Formatter<'_>,
359 ) -> core::fmt::Result {
360 f.debug_tuple("BorrowCompat").field(&self.0).finish()
361 }
362}
363
364impl<T> core::fmt::Display for BorrowCompat<T>
365where
366 T: core::fmt::Display,
367{
368 fn fmt(
369 &self,
370 f: &mut core::fmt::Formatter<'_>,
371 ) -> core::fmt::Result {
372 self.0.fmt(f)
373 }
374}