1use crate::{Decoder, Encoder};
2use thiserror::Error;
3
4#[derive(Debug, Error)]
5pub enum HybridCoderError<E> {
6 #[error("Not implemented: {0}")]
7 NotImplemented(&'static str),
8 #[error("Decoding error")]
9 Coder(#[from] E),
10}
11
12pub trait HybridDecoder<T, E: ?Sized> {
13 type Error;
14
15 fn is_binary_decoder() -> bool;
16
17 fn decode_str(_val: &str) -> Result<T, HybridCoderError<Self::Error>> {
18 Err(HybridCoderError::NotImplemented(
19 "You're trying to decode from a string. This codec is binary.",
20 ))
21 }
22
23 fn decode_bin(_val: &[u8]) -> Result<T, HybridCoderError<Self::Error>> {
24 Err(HybridCoderError::NotImplemented(
25 "You're trying to decode from a byte slice. This codec is a string codec.",
26 ))
27 }
28}
29
30impl<T, D> HybridDecoder<T, [u8]> for D
31where
32 D: Decoder<T, Encoded = [u8]>,
33{
34 type Error = D::Error;
35
36 #[inline(always)]
37 fn is_binary_decoder() -> bool {
38 true
39 }
40
41 fn decode_bin(val: &[u8]) -> Result<T, HybridCoderError<Self::Error>> {
42 Ok(D::decode(val)?)
43 }
44}
45
46impl<T, D> HybridDecoder<T, str> for D
47where
48 D: Decoder<T, Encoded = str>,
49{
50 type Error = D::Error;
51
52 #[inline(always)]
53 fn is_binary_decoder() -> bool {
54 false
55 }
56
57 fn decode_str(val: &str) -> Result<T, HybridCoderError<Self::Error>> {
58 Ok(D::decode(val)?)
59 }
60}
61
62pub trait HybridEncoder<T, E> {
63 type Error;
64
65 fn is_binary_encoder() -> bool;
66
67 fn encode_str(_val: &T) -> Result<String, HybridCoderError<Self::Error>> {
68 Err(HybridCoderError::NotImplemented(
69 "You're trying to encode into a string. This codec is binary.",
70 ))
71 }
72
73 fn encode_bin(_val: &T) -> Result<Vec<u8>, HybridCoderError<Self::Error>> {
74 Err(HybridCoderError::NotImplemented(
75 "You're trying to encode into a byte vec. This codec is a string codec.",
76 ))
77 }
78}
79
80impl<T, E> HybridEncoder<T, Vec<u8>> for E
81where
82 E: Encoder<T, Encoded = Vec<u8>>,
83{
84 type Error = E::Error;
85
86 #[inline(always)]
87 fn is_binary_encoder() -> bool {
88 true
89 }
90
91 fn encode_bin(val: &T) -> Result<Vec<u8>, HybridCoderError<Self::Error>> {
92 Ok(E::encode(val)?)
93 }
94}
95
96impl<T, E> HybridEncoder<T, String> for E
97where
98 E: Encoder<T, Encoded = String>,
99{
100 type Error = E::Error;
101
102 #[inline(always)]
103 fn is_binary_encoder() -> bool {
104 false
105 }
106
107 fn encode_str(val: &T) -> Result<String, HybridCoderError<Self::Error>> {
108 Ok(E::encode(val)?)
109 }
110}