isr_cache/
codec.rs

1use std::io::Write;
2
3use isr_core::Profile;
4
5/// A codec for encoding and decoding profiles.
6pub trait Codec {
7    /// The file extension for this codec.
8    const EXTENSION: &'static str;
9
10    /// The error type for encoding.
11    type EncodeError: std::error::Error + Send + Sync + 'static;
12
13    /// The error type for decoding.
14    type DecodeError: std::error::Error + Send + Sync + 'static;
15
16    /// Encodes a profile into the given writer.
17    fn encode(writer: impl Write, profile: &Profile) -> Result<(), Self::EncodeError>;
18
19    /// Decodes a profile from the given slice.
20    fn decode(slice: &[u8]) -> Result<Profile<'_>, Self::DecodeError>;
21}
22
23/// A codec for the bincode format.
24///
25/// Provides a compact binary representation of profiles.
26#[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/// A codec for the JSON format.
49///
50/// Provides human-readable profiles.
51#[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/// A codec for the MessagePack format.
71///
72/// Provides a compact binary representation of profiles.
73#[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}