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