1use std::io::Write;
2
3use isr_core::Profile;
4
5pub trait Codec {
7 const EXTENSION: &'static str;
9
10 type EncodeError: std::error::Error + Send + Sync + 'static;
12
13 type DecodeError: std::error::Error + Send + Sync + 'static;
15
16 fn encode(writer: impl Write, profile: &Profile) -> Result<(), Self::EncodeError>;
18
19 fn decode(slice: &[u8]) -> Result<Profile<'_>, Self::DecodeError>;
21}
22
23#[cfg(feature = "codec-bincode")]
27pub struct BincodeCodec;
28
29#[cfg(feature = "codec-bincode")]
30impl Codec for BincodeCodec {
31 const EXTENSION: &'static str = "bin";
32
33 type EncodeError = bincode::error::EncodeError;
34 type DecodeError = bincode::error::DecodeError;
35
36 fn encode(mut writer: impl Write, profile: &Profile) -> Result<(), Self::EncodeError> {
37 bincode::serde::encode_into_std_write(profile, &mut writer, bincode::config::standard())?;
38 Ok(())
39 }
40
41 fn decode(slice: &[u8]) -> Result<Profile<'_>, Self::DecodeError> {
42 let (result, _bytes_read) =
43 bincode::serde::borrow_decode_from_slice(slice, bincode::config::standard())?;
44 Ok(result)
45 }
46}
47
48#[cfg(feature = "codec-json")]
52pub struct JsonCodec;
53
54#[cfg(feature = "codec-json")]
55impl Codec for JsonCodec {
56 const EXTENSION: &'static str = "json";
57
58 type EncodeError = serde_json::Error;
59 type DecodeError = serde_json::Error;
60
61 fn encode(writer: impl Write, profile: &Profile) -> Result<(), Self::EncodeError> {
62 serde_json::to_writer_pretty(writer, profile)
63 }
64
65 fn decode(slice: &[u8]) -> Result<Profile<'_>, Self::DecodeError> {
66 serde_json::from_slice(slice)
67 }
68}
69
70#[cfg(feature = "codec-msgpack")]
74pub struct MsgpackCodec;
75
76#[cfg(feature = "codec-msgpack")]
77impl Codec for MsgpackCodec {
78 const EXTENSION: &'static str = "msgpack";
79
80 type EncodeError = rmp_serde::encode::Error;
81 type DecodeError = rmp_serde::decode::Error;
82
83 fn encode(mut writer: impl Write, profile: &Profile) -> Result<(), Self::EncodeError> {
84 rmp_serde::encode::write(&mut writer, profile)
85 }
86
87 fn decode(slice: &[u8]) -> Result<Profile<'_>, Self::DecodeError> {
88 rmp_serde::from_slice(slice)
89 }
90}