Skip to main content

messagepack_core/encode/
mod.rs

1//! Encoding primitives for MessagePack.
2//!
3//! This module exposes the `Encode` trait and a number of small helper
4//! encoders for arrays, maps, strings and binary data.
5
6pub mod array;
7pub mod bin;
8pub mod bool;
9pub mod float;
10pub mod int;
11pub mod map;
12pub mod nil;
13pub mod str;
14
15/// Helper to encode raw binary blobs using `bin8/16/32` formats.
16pub use bin::BinaryEncoder;
17/// Helpers to encode MessagePack maps from various sources.
18pub use map::{MapDataEncoder, MapEncoder, MapFormatEncoder, MapSliceEncoder};
19/// Encode the MessagePack `nil` value.
20pub use nil::NilEncoder;
21
22use crate::{Format, io::IoWrite};
23
24/// MessagePack encode error
25#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq)]
26pub enum Error<T> {
27    /// Error produced by the underlying writer.
28    Io(T),
29    /// Cannot mapped messagepack format
30    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
52/// A type which can be encoded to MessagePack.
53pub trait Encode {
54    /// Encode this value to MessagePack and write bytes to `writer`.
55    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}