Skip to main content

titan_api_codec/enc/
common.rs

1//! Common traits and implementations for binary encoding of messages.
2
3use bytes::Bytes;
4use serde::ser::Serialize;
5use thiserror::Error;
6
7use crate::transform::BinaryTransform;
8
9/// Possible errors that can occur while encoding messages.
10#[derive(Error, Debug)]
11pub enum EncodeError {
12    /// Serialization to the data format failed.
13    #[error("Failed to serialize message to data format")]
14    SerializationFailed(#[from] Box<dyn std::error::Error + Send + Sync>),
15    /// Transformation of the serialized data failed (ex. compression).
16    #[error("Failed to apply transform to serialized data")]
17    TransformFailed(#[from] std::io::Error),
18}
19
20/// An encoder that can transform a serde-serializable object into binary data.
21pub trait Encoder {
22    /// Encode the specified object and return the bytes representing the encoded value.
23    fn encode<T>(&self, value: &T) -> Result<Bytes, EncodeError>
24    where
25        T: Serialize;
26
27    /// Encode the specified object and return the bytes representing the encoded value, possibly
28    /// mutating the state of the encoder.
29    fn encode_mut<T>(&mut self, value: &T) -> Result<Bytes, EncodeError>
30    where
31        T: Serialize,
32    {
33        self.encode(value)
34    }
35
36    /// Takes the encoder and applies the given transform to data produced by it.
37    fn transform<BT>(self, transformer: BT) -> TransformedEncoder<Self, BT>
38    where
39        Self: Sized,
40        BT: BinaryTransform,
41    {
42        TransformedEncoder::new(self, transformer)
43    }
44}
45
46/// An encoder that applies a transform to data encoded by another encoder.
47pub struct TransformedEncoder<E: Encoder, BT: BinaryTransform> {
48    encoder: E,
49    transformer: BT,
50}
51
52impl<E: Encoder, BT: BinaryTransform> TransformedEncoder<E, BT> {
53    // Wraps `encoder`, applying `transformer` to any encoded data.
54    fn new(encoder: E, transformer: BT) -> Self {
55        Self {
56            encoder,
57            transformer,
58        }
59    }
60}
61
62impl<E: Encoder, BT: BinaryTransform> Encoder for TransformedEncoder<E, BT> {
63    fn encode<T>(&self, value: &T) -> Result<Bytes, EncodeError>
64    where
65        T: Serialize,
66    {
67        self.transformer
68            .transform(self.encoder.encode(value)?)
69            .map_err(EncodeError::TransformFailed)
70    }
71
72    fn encode_mut<T>(&mut self, value: &T) -> Result<Bytes, EncodeError>
73    where
74        T: Serialize,
75    {
76        self.transformer
77            .transform_mut(self.encoder.encode_mut(value)?)
78            .map_err(EncodeError::TransformFailed)
79    }
80}