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