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;
14mod timestamp;
15
16/// Helper to encode raw binary blobs using `bin8/16/32` formats.
17pub use bin::BinaryEncoder;
18/// Helpers to encode MessagePack maps from various sources.
19pub use map::{MapDataEncoder, MapEncoder, MapFormatEncoder, MapSliceEncoder};
20/// Encode the MessagePack `nil` value.
21pub use nil::NilEncoder;
22
23use crate::{Format, io::IoWrite};
24
25/// MessagePack encode error
26#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq)]
27pub enum Error<T> {
28    /// Error produced by the underlying writer.
29    Io(T),
30    /// Cannot mapped messagepack format
31    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
53/// A type which can be encoded to MessagePack.
54pub trait Encode<W>
55where
56    W: IoWrite,
57{
58    /// Encode this value to MessagePack and write bytes to `writer`.
59    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}