1use thiserror::Error;
8
9#[derive(Debug, Clone, PartialEq, Error)]
10pub enum CodecError {
11 #[error("Encode error: {0}")]
12 Encode(String),
13 #[error("Decode error: {0}")]
14 Decode(String),
15}
16
17pub trait Codec<T> {
18 fn encode(d: &T) -> Result<Vec<u8>, CodecError>;
19 fn decode(e: &[u8]) -> Result<T, CodecError>;
20}
21
22pub trait CodecName {
23 fn name() -> &'static str;
24}
25
26pub struct PassthroughCodec;
30
31impl CodecName for PassthroughCodec {
32 fn name() -> &'static str {
33 "native"
34 }
35}
36
37impl<T: Send + Sync + 'static> Codec<T> for PassthroughCodec {
38 fn encode(_: &T) -> Result<Vec<u8>, CodecError> {
39 Err(CodecError::Encode("PassthroughCodec cannot encode".into()))
40 }
41 fn decode(_: &[u8]) -> Result<T, CodecError> {
42 Err(CodecError::Decode("PassthroughCodec cannot decode".into()))
43 }
44}
45
46#[derive(Debug, Clone)]
49pub struct TextCodec;
50
51impl CodecName for TextCodec {
52 fn name() -> &'static str {
53 "text"
54 }
55}
56
57impl Codec<String> for TextCodec {
58 fn encode(d: &String) -> Result<Vec<u8>, CodecError> {
59 Ok(d.as_bytes().to_vec())
60 }
61 fn decode(e: &[u8]) -> Result<String, CodecError> {
62 String::from_utf8(e.to_vec()).map_err(|e| CodecError::Decode(e.to_string()))
63 }
64}