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<W>
54where
55    W: IoWrite,
56{
57    /// Encode this value to MessagePack and write bytes to `writer`.
58    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}