Skip to main content

mill_rpc_core/
codec.rs

1use crate::error::RpcError;
2use serde::{de::DeserializeOwned, Serialize};
3
4/// Supported codec types.
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum CodecType {
7    Bincode,
8}
9
10/// Codec for serializing/deserializing RPC payloads.
11#[derive(Debug, Clone)]
12pub struct Codec {
13    codec_type: CodecType,
14}
15
16impl Codec {
17    pub fn bincode() -> Self {
18        Self {
19            codec_type: CodecType::Bincode,
20        }
21    }
22
23    pub fn codec_type(&self) -> CodecType {
24        self.codec_type
25    }
26
27    /// Serialize a value to bytes.
28    pub fn serialize<T: Serialize>(&self, value: &T) -> Result<Vec<u8>, RpcError> {
29        match self.codec_type {
30            CodecType::Bincode => bincode::serialize(value)
31                .map_err(|e| RpcError::codec_error(format!("serialize: {}", e))),
32        }
33    }
34
35    /// Deserialize bytes to a value.
36    pub fn deserialize<T: DeserializeOwned>(&self, data: &[u8]) -> Result<T, RpcError> {
37        match self.codec_type {
38            CodecType::Bincode => bincode::deserialize(data)
39                .map_err(|e| RpcError::codec_error(format!("deserialize: {}", e))),
40        }
41    }
42}
43
44impl Default for Codec {
45    fn default() -> Self {
46        Self::bincode()
47    }
48}