messagepack_core/encode/
mod.rs1pub mod array;
7pub mod bin;
8pub mod bool;
9pub mod float;
10pub mod int;
11pub mod map;
12pub mod nil;
13pub mod str;
14
15pub use bin::BinaryEncoder;
17pub use map::{MapDataEncoder, MapEncoder, MapFormatEncoder, MapSliceEncoder};
19pub use nil::NilEncoder;
21
22use crate::{Format, io::IoWrite};
23
24#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq)]
26pub enum Error<T> {
27 Io(T),
29 InvalidFormat,
31}
32
33impl<T> From<T> for Error<T> {
34 fn from(value: T) -> Self {
35 Error::Io(value)
36 }
37}
38
39impl<T: core::fmt::Display> core::fmt::Display for Error<T> {
40 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
41 match self {
42 Error::Io(e) => write!(f, "{}", e),
43 Error::InvalidFormat => write!(f, "Cannot encode value"),
44 }
45 }
46}
47
48impl<T: core::error::Error> core::error::Error for Error<T> {}
49
50type Result<T, E> = ::core::result::Result<T, Error<E>>;
51
52pub trait Encode<W>
54where
55 W: IoWrite,
56{
57 fn encode(&self, writer: &mut W) -> Result<usize, W::Error>;
59}
60
61macro_rules! deref_impl {
62 (
63 $(#[$attr:meta])*
64 <$($desc:tt)+
65 ) => {
66 $(#[$attr])*
67 impl<$($desc)+
68 {
69 fn encode(&self, writer: &mut W) -> Result<usize, <W as IoWrite>::Error> {
70 (**self).encode(writer)
71 }
72 }
73 };
74}
75
76deref_impl! {
77 <V, W> Encode<W> for &V
78 where
79 V: Encode<W>,
80 W: IoWrite,
81}
82
83deref_impl! {
84 <V, W> Encode<W> for &mut V
85 where
86 V: Encode<W>,
87 W: IoWrite,
88}
89
90impl<W> Encode<W> for Format
91where
92 W: IoWrite,
93{
94 fn encode(&self, writer: &mut W) -> Result<usize, <W as IoWrite>::Error> {
95 writer.write(&self.as_slice())?;
96 Ok(1)
97 }
98}