pub trait Decode<'de>: Sized {
// Required method
fn decode(r: &mut &'de [u8], context: &Context) -> Result<Self, DecodeError>;
}
Expand description
A general purpose trait for msgpack deserialization.
Reads self
from a reader supplied in r
.
For most use cases this trait can be derived (#[derive(Decode)]
).
When deriving the trait for a structure it’s possible to additionally specify
if the structure should be represented as MP_MAP
or as an MP_ARRAY
.
MP_ARRAY
is chosen by default for compactness. To deserailize a structure as an MP_MAP
add [encode(as_map)
] attribute to it.
E.g. given let foo = Foo { a: 1, b: 3}
As MP_ARRAY
foo
should be identical to (1, 3)
during serialization.
As MP_MAP
foo
should be identical to HashMap<String, usize>
with
keys "a"
and "b"
and values 1
, 3
accordingly.
context.style
let’s you override as_map
attribute if it is defined for a struct.
does not override behavior of std types. To override supply Encode::ForceAsMap
or
StructStyle::ForceAsArray
. To leave the behavior up to the struct set it to Encode::Default
.
It is also possible to put #[encode(as_raw)]
attribute on fields of structs or variants of enums
to interpret field or variant value as raw MessagePack value. This will validate them at runtime
and directly write to or read from buffer.
Fields with type Option<T>
can be skipped in msgpack if decoding MP_MAP.
In case of an MP_ARRAY (if #[encode(allow_array_optionals)]
is enabled) only last fields
with type of Option<T>
can be skipped.
It should replace tuple::Decode
when it’s ready.
§Example
use tarantool::msgpack::Decode;
#[derive(Decode, Debug, PartialEq)]
struct Foo {
a: usize,
b: usize,
};
let buffer: Vec<u8> = vec![0x92, 0x01, 0x03];
let foo = <Foo as Decode>::decode(&mut &buffer[..], &Default::default()).unwrap();
assert_eq!(foo, Foo {a: 1, b: 3});
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.