Skip to main content

bincode_purplecoin/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//! - [decode_borrowed_from_slice]
5//! - [decode_from_slice]
6//! - [encode_to_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::{Decode, Encode};
19//! # use serde_derive::{Deserialize, Serialize};
20//! #[derive(Serialize, Deserialize)]
21//! # #[serde(crate = "serde_incl")]
22//! pub struct SerdeType {
23//!     // ...
24//! }
25//!
26//! #[derive(Decode, Encode)]
27//! pub struct StructWithSerde {
28//!     #[bincode(with_serde)]
29//!     pub serde: SerdeType,
30//! }
31//!
32//! #[derive(Decode, Encode)]
33//! pub enum EnumWithSerde {
34//!     Unit(#[bincode(with_serde)] SerdeType),
35//!     Struct {
36//!         #[bincode(with_serde)]
37//!         serde: SerdeType,
38//!     },
39//! }
40//! # }
41//! ```
42//!
43//! # `alloc` and `no_std`
44//!
45//! The `serde` feature enables both `alloc` and `std` at this point in time.
46//! To use bincode and serde on no_std targets, try one of the following features:
47//!
48//! - `serde_alloc`: enables `serde` and `alloc`
49//! - `serde_no_std`: enables `serde` without `alloc` or `std`
50//!
51//! # Known issues
52//!
53//! Currently the `serde` feature will automatically enable the `alloc` and `std` feature. If you're running in a `#[no_std]` environment consider using bincode's own derive macros.
54//!
55//! 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.
56//! - `#[serde(skip)]`
57//! - `#[serde(skip_serializing)]`
58//! - `#[serde(skip_deserializing)]`
59//! - `#[serde(skip_serializing_if = "path")]`
60//! - `#[serde(flatten)]`
61//! - `#[serde(untagged)]`
62//!
63//! **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.
64//!
65//! [Decode]: ../de/trait.Decode.html
66//! [Encode]: ../enc/trait.Encode.html
67
68mod de_borrowed;
69mod de_owned;
70mod ser;
71
72pub use self::de_borrowed::*;
73pub use self::de_owned::*;
74pub use self::ser::*;
75
76/// A serde-specific error that occurred while decoding.
77#[derive(Debug, PartialEq)]
78#[non_exhaustive]
79pub enum DecodeError {
80    /// Bincode does not support serde's `any` decoding feature
81    AnyNotSupported,
82
83    /// Bincode does not support serde identifiers
84    IdentifierNotSupported,
85
86    /// Bincode does not support serde's `ignored_any`
87    IgnoredAnyNotSupported,
88
89    /// Serde tried decoding a borrowed value from an owned reader. Use `serde_decode_borrowed_from_*` instead
90    CannotBorrowOwnedData,
91
92    /// Serde does not support skipping fixed array lengths
93    SkipFixedArrayLengthNotSupported,
94
95    /// Could not allocate data like `String` and `Vec<u8>`
96    #[cfg(not(feature = "alloc"))]
97    CannotAllocate,
98
99    /// Custom serde error but bincode is unable to allocate a string. Set a breakpoint where this is thrown for more information.
100    #[cfg(not(feature = "alloc"))]
101    CustomError,
102}
103
104#[cfg(feature = "alloc")]
105impl serde_incl::de::Error for crate::error::DecodeError {
106    fn custom<T>(msg: T) -> Self
107    where
108        T: core::fmt::Display,
109    {
110        use alloc::string::ToString;
111        Self::OtherString(msg.to_string())
112    }
113}
114
115#[cfg(not(feature = "std"))]
116impl serde_incl::de::StdError for crate::error::DecodeError {}
117
118#[cfg(not(feature = "alloc"))]
119impl serde_incl::de::Error for crate::error::DecodeError {
120    fn custom<T>(_: T) -> Self
121    where
122        T: core::fmt::Display,
123    {
124        DecodeError::CustomError.into()
125    }
126}
127
128#[allow(clippy::from_over_into)]
129impl Into<crate::error::DecodeError> for DecodeError {
130    fn into(self) -> crate::error::DecodeError {
131        crate::error::DecodeError::Serde(self)
132    }
133}
134
135/// A serde-specific error that occurred while encoding.
136#[derive(Debug, PartialEq)]
137#[non_exhaustive]
138pub enum EncodeError {
139    /// Serde provided bincode with a sequence without a length, which is not supported in bincode
140    SequenceMustHaveLength,
141
142    /// Serde does not support skipping fixed array lengths
143    SkipFixedArrayLengthNotSupported,
144
145    /// [Serializer::collect_str] got called but bincode was unable to allocate memory.
146    #[cfg(not(feature = "alloc"))]
147    CannotCollectStr,
148
149    /// Custom serde error but bincode is unable to allocate a string. Set a breakpoint where this is thrown for more information.
150    #[cfg(not(feature = "alloc"))]
151    CustomError,
152}
153
154#[allow(clippy::from_over_into)]
155impl Into<crate::error::EncodeError> for EncodeError {
156    fn into(self) -> crate::error::EncodeError {
157        crate::error::EncodeError::Serde(self)
158    }
159}
160
161#[cfg(feature = "alloc")]
162impl serde_incl::ser::Error for crate::error::EncodeError {
163    fn custom<T>(msg: T) -> Self
164    where
165        T: core::fmt::Display,
166    {
167        use alloc::string::ToString;
168
169        Self::OtherString(msg.to_string())
170    }
171}
172
173#[cfg(not(feature = "std"))]
174impl serde_incl::de::StdError for crate::error::EncodeError {}
175
176#[cfg(not(feature = "alloc"))]
177impl serde_incl::ser::Error for crate::error::EncodeError {
178    fn custom<T>(_: T) -> Self
179    where
180        T: core::fmt::Display,
181    {
182        EncodeError::CustomError.into()
183    }
184}
185
186/// Wrapper struct that implements [Decode] and [Encode] on any type that implements serde's [DeserializeOwned] and [Serialize] respectively.
187///
188/// This works for most types, but if you're dealing with borrowed data consider using [BorrowCompat] instead.
189///
190/// [Decode]: ../de/trait.Decode.html
191/// [Encode]: ../enc/trait.Encode.html
192/// [DeserializeOwned]: https://docs.rs/serde/1/serde/de/trait.DeserializeOwned.html
193/// [Serialize]: https://docs.rs/serde/1/serde/trait.Serialize.html
194pub struct Compat<T>(pub T);
195
196impl<T> crate::Decode for Compat<T>
197where
198    T: serde_incl::de::DeserializeOwned,
199{
200    fn decode<D: crate::de::Decoder>(decoder: &mut D) -> Result<Self, crate::error::DecodeError> {
201        let serde_decoder = de_owned::SerdeDecoder { de: decoder };
202        T::deserialize(serde_decoder).map(Compat)
203    }
204}
205
206impl<T> crate::Encode for Compat<T>
207where
208    T: serde_incl::Serialize,
209{
210    fn encode<E: crate::enc::Encoder>(
211        &self,
212        encoder: &mut E,
213    ) -> Result<(), crate::error::EncodeError> {
214        let serializer = ser::SerdeEncoder { enc: encoder };
215        self.0.serialize(serializer)?;
216        Ok(())
217    }
218}
219
220/// Wrapper struct that implements [BorrowDecode] and [Encode] on any type that implements serde's [Deserialize] and [Serialize] respectively. This is mostly used on `&[u8]` and `&str`, for other types consider using [Compat] instead.
221///
222/// [BorrowDecode]: ../de/trait.BorrowDecode.html
223/// [Encode]: ../enc/trait.Encode.html
224/// [Deserialize]: https://docs.rs/serde/1/serde/de/trait.Deserialize.html
225/// [Serialize]: https://docs.rs/serde/1/serde/trait.Serialize.html
226pub struct BorrowCompat<T>(pub T);
227
228impl<'de, T> crate::de::BorrowDecode<'de> for BorrowCompat<T>
229where
230    T: serde_incl::de::Deserialize<'de>,
231{
232    fn borrow_decode<D: crate::de::BorrowDecoder<'de>>(
233        decoder: &mut D,
234    ) -> Result<Self, crate::error::DecodeError> {
235        let serde_decoder = de_borrowed::SerdeDecoder {
236            de: decoder,
237            pd: core::marker::PhantomData,
238        };
239        T::deserialize(serde_decoder).map(BorrowCompat)
240    }
241}
242
243impl<T> crate::Encode for BorrowCompat<T>
244where
245    T: serde_incl::Serialize,
246{
247    fn encode<E: crate::enc::Encoder>(
248        &self,
249        encoder: &mut E,
250    ) -> Result<(), crate::error::EncodeError> {
251        let serializer = ser::SerdeEncoder { enc: encoder };
252        self.0.serialize(serializer)?;
253        Ok(())
254    }
255}