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 {
54 fn encode<W: IoWrite>(&self, writer: &mut W) -> Result<usize, W::Error>;
56}
57
58macro_rules! deref_impl {
59 (
60 $(#[$attr:meta])*
61 <$($desc:tt)+
62 ) => {
63 $(#[$attr])*
64 impl<$($desc)+
65 {
66 fn encode<W: IoWrite>(&self, writer: &mut W) -> Result<usize, <W as IoWrite>::Error> {
67 (**self).encode(writer)
68 }
69 }
70 };
71}
72
73deref_impl! {
74 <V> Encode for &V
75 where
76 V: Encode,
77}
78
79deref_impl! {
80 <V> Encode for &mut V
81 where
82 V: Encode,
83}
84
85#[cfg(feature = "alloc")]
86deref_impl! {
87 <V> Encode for alloc::boxed::Box<V>
88 where
89 V: Encode + ?Sized,
90}
91
92impl Encode for Format {
93 fn encode<W: IoWrite>(&self, writer: &mut W) -> Result<usize, <W as IoWrite>::Error> {
94 writer.write(&self.as_slice())?;
95 Ok(1)
96 }
97}