1use crate::error::RpcError;
2use serde::{de::DeserializeOwned, Serialize};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum CodecType {
7 Bincode,
8}
9
10#[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 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 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}