usecrate::config::sealed::SerializerConfig as _; use std::convert::TryInto; use std::error; use std::fmt::{self, Display, Formatter}; use std::io::{self, Cursor, ErrorKind, Read}; use std::marker::PhantomData; use std::num::TryFromIntError; use std::str::{self, Utf8Error};
use byteorder::{self, ReadBytesExt};
use serde; use serde::de::value::SeqDeserializer; use serde::de::{self, Deserialize, DeserializeOwned, DeserializeSeed, Unexpected, Visitor}; use serde::forward_to_deserialize_any;
use rmp; use rmp::decode::{self, DecodeStringError, MarkerReadError, NumValueReadError, RmpRead, ValueReadError}; use rmp::Marker;
/// Enum representing errors that can occur while decoding MessagePack data. #[derive(Debug)] pubenum Error { /// The enclosed I/O error occurred while trying to read a MessagePack /// marker.
InvalidMarkerRead(io::Error), /// The enclosed I/O error occurred while trying to read the encoded /// MessagePack data.
InvalidDataRead(io::Error), /// A mismatch occurred between the decoded and expected value types.
TypeMismatch(Marker), /// A numeric cast failed due to an out-of-range error.
OutOfRange, /// A decoded array did not have the enclosed expected length.
LengthMismatch(u32), /// An otherwise uncategorized error occurred. See the enclosed `String` for /// details.
Uncategorized(String), /// A general error occurred while deserializing the expected type. See the /// enclosed `String` for details.
Syntax(String), /// An encoded string could not be parsed as UTF-8.
Utf8Error(Utf8Error), /// The depth limit was exceeded.
DepthLimitExceeded,
}
macro_rules! depth_count(
( $counter:expr, $expr:expr ) => {
{
$counter -= 1; if $counter == 0 { return Err(Error::DepthLimitExceeded)
} let res = $expr;
$counter += 1;
res
}
}
);
/// A Deserializer that reads bytes from a buffer. /// /// # Note /// /// All instances of `ErrorKind::Interrupted` are handled by this function and the underlying /// operation is retried. #[derive(Debug)] pubstruct Deserializer<R, C = DefaultConfig> {
rd: R,
_config: PhantomData<C>,
is_human_readable: bool,
marker: Option<Marker>,
depth: u16,
}
impl<R: Read> Deserializer<ReadReader<R>, DefaultConfig> { /// Constructs a new `Deserializer` by consuming the given reader. #[inline] pubfn new(rd: R) -> Self { Self {
rd: ReadReader::new(rd),
_config: PhantomData,
is_human_readable: DefaultConfig.is_human_readable(), // Cached marker in case of deserializing optional values.
marker: None,
depth: 1024,
}
}
}
impl<R: Read, C> Deserializer<ReadReader<R>, C> { /// Gets a reference to the underlying reader in this decoder. #[inline(always)] pubfn get_ref(&self) -> &R {
&self.rd.rd
}
/// Gets a mutable reference to the underlying reader in this decoder. #[inline(always)] pubfn get_mut(&mutself) -> &mut R {
&mutself.rd.rd
}
/// Consumes this deserializer returning the underlying reader. #[inline] pubfn into_inner(self) -> R { self.rd.rd
}
}
impl<R: Read, C: SerializerConfig> Deserializer<R, C> { /// Consumes this deserializer and returns a new one, which will deserialize types with /// human-readable representations (`Deserializer::is_human_readable` will return `true`). /// /// This is primarily useful if you need to interoperate with serializations produced by older /// versions of `rmp-serde`. #[inline] pubfn with_human_readable(self) -> Deserializer<R, HumanReadableConfig<C>> { let Deserializer { rd, _config: _, is_human_readable: _, marker, depth } = self;
Deserializer {
rd,
is_human_readable: true,
_config: PhantomData,
marker,
depth,
}
}
/// Consumes this deserializer and returns a new one, which will deserialize types with /// binary representations (`Deserializer::is_human_readable` will return `false`). /// /// This is the default MessagePack deserialization mechanism, consuming the most compact /// representation. #[inline] pubfn with_binary(self) -> Deserializer<R, BinaryConfig<C>> { let Deserializer { rd, _config: _, is_human_readable: _, marker, depth } = self;
Deserializer {
rd,
is_human_readable: false,
_config: PhantomData,
marker,
depth,
}
}
}
impl<R: AsRef<[u8]>> Deserializer<ReadReader<Cursor<R>>> { /// Returns the current position of this deserializer, i.e. how many bytes were read. #[inline(always)] pubfn position(&self) -> u64 { self.rd.rd.position()
}
}
impl<'de, R> Deserializer<ReadRefReader<'de, R>> where
R: AsRef<[u8]> + ?Sized,
{ /// Constructs a new `Deserializer` from the given byte slice. #[inline(always)] pubfn from_read_ref(rd: &'de R) -> Self {
Deserializer {
rd: ReadRefReader::new(rd),
is_human_readable: DefaultConfig.is_human_readable(),
_config: PhantomData,
marker: None,
depth: 1024,
}
}
/// Gets a reference to the underlying reader in this decoder. #[inline(always)] #[must_use] pubfn get_ref(&self) -> &R { self.rd.whole_slice
}
}
impl<'de, R: ReadSlice<'de>, C: SerializerConfig> Deserializer<R, C> { /// Changes the maximum nesting depth that is allowed #[inline(always)] pubfn set_max_depth(&mutself, depth: usize) { self.depth = depth.min(u16::MAX as _) as u16;
}
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>
{ // # Important // // If a nested Option `o ∈ { Option<Opion<t>>, Option<Option<Option<t>>>, ..., Option<Option<...Option<t>...> }` // is visited for the first time, the marker (read from the underlying Reader) will determine // `o`'s innermost type `t`. // For subsequent visits of `o` the marker will not be re-read again but kept until type `t` // is visited. // // # Note // // Round trips of Options where `Option<t> = None` such as `Some(None)` will fail because // they are just seriialized as `nil`. The serialization format has probably to be changed // to solve this. But as serde_json behaves the same, I think it's not worth doing this. let marker = self.take_or_read_marker()?;
if marker == Marker::Null {
visitor.visit_none()
} else { // Keep the marker until `o`'s innermost type `t` is visited. self.marker = Some(marker);
visitor.visit_some(self)
}
}
fn deserialize_enum<V>(self, _name: &str, _variants: &[&str], visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>
{ let marker = self.peek_or_read_marker()?; match rmp::decode::marker_to_len(&mutself.rd, marker) {
Ok(len) => match len { // Enums are either encoded as maps with a single K/V pair // where the K = the variant & V = associated data // or as just the variant 1 => { self.marker = None;
visitor.visit_enum(VariantAccess::new(self))
}
n => Err(Error::LengthMismatch(n)),
}, // TODO: Check this is a string
Err(_) => visitor.visit_enum(UnitVariantAccess::new(self)),
}
}
fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>
{ if name == MSGPACK_EXT_STRUCT_NAME { let marker = self.take_or_read_marker()?;
let len = ext_len(&mutself.rd, marker)?; let ext_de = ExtDeserializer::new(self, len); return visitor.visit_newtype_struct(ext_de);
}
visitor.visit_newtype_struct(self)
}
fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>
{ // We need to special case this so that [] is treated as a unit struct when asked for, // but as a sequence otherwise. This is because we serialize unit structs as [] rather // than as 'nil'. matchself.take_or_read_marker()? {
Marker::Null | Marker::FixArray(0) => visitor.visit_unit(),
marker => { self.marker = Some(marker); self.deserialize_any(visitor)
}
}
}
/// Unification of both borrowed and non-borrowed reference types. #[derive(Clone, Copy, Debug, PartialEq)] pubenum Reference<'b, 'c, T: ?Sized + 'static> { /// The reference is pointed at data that was borrowed.
Borrowed(&'b T), /// The reference is pointed at data that was copied.
Copied(&'c T),
}
/// Extends the `Read` trait by allowing to read slices directly by borrowing bytes. /// /// Used to allow zero-copy reading. pubtrait ReadSlice<'de>: Read { /// Reads the exact number of bytes from the underlying byte-array. fn read_slice<'a>(&'a mutself, len: usize) -> Result<Reference<'de, 'a, [u8]>, io::Error>;
}
/// Deserialize an instance of type `T` from an I/O stream of MessagePack. /// /// # Errors /// /// This conversion can fail if the structure of the Value does not match the structure expected /// by `T`. It can also fail if the structure is correct but `T`'s implementation of `Deserialize` /// decides that something is wrong with the data, for example required struct fields are missing. #[inline] pubfn from_read<R, T>(rd: R) -> Result<T, Error> where R: Read,
T: DeserializeOwned
{
Deserialize::deserialize(&mut Deserializer::new(rd))
}
/// Deserialize a temporary scope-bound instance of type `T` from a slice, with zero-copy if possible. /// /// Deserialization will be performed in zero-copy manner whenever it is possible, borrowing the /// data from the slice itself. For example, strings and byte-arrays won't copied. /// /// # Errors /// /// This conversion can fail if the structure of the Value does not match the structure expected /// by `T`. It can also fail if the structure is correct but `T`'s implementation of `Deserialize` /// decides that something is wrong with the data, for example required struct fields are missing. /// /// # Examples /// /// ``` /// use serde::Deserialize; /// /// // Encoded `["Bobby", 8]`. /// let buf = [0x92, 0xa5, 0x42, 0x6f, 0x62, 0x62, 0x79, 0x8]; /// /// #[derive(Debug, Deserialize, PartialEq)] /// struct Dog<'a> { /// name: &'a str, /// age: u8, /// } /// /// assert_eq!(Dog { name: "Bobby", age: 8 }, rmp_serde::from_slice(&buf).unwrap()); /// ``` #[inline(always)] #[allow(deprecated)] pubfn from_slice<'a, T>(input: &'a [u8]) -> Result<T, Error> where
T: Deserialize<'a>,
{
from_read_ref(input)
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.