Skip to main content

kape_redis/
codec.rs

1use crate::RedisBackendError;
2
3/// Encodes typed keys and values at the `Redis` adapter boundary.
4pub trait RedisCodec<K, V>: Send + Sync + 'static {
5    /// Encodes a typed key as `Redis` key bytes.
6    ///
7    /// # Errors
8    ///
9    /// Returns a backend error whose source is the codec error when the key
10    /// cannot be represented.
11    fn encode_key(&self, key: &K) -> Result<Vec<u8>, RedisBackendError>;
12
13    /// Encodes a typed value.
14    ///
15    /// # Errors
16    ///
17    /// Returns a backend error whose source is the codec error when the value
18    /// cannot be represented.
19    fn encode_value(&self, value: &V) -> Result<Vec<u8>, RedisBackendError>;
20
21    /// Decodes a typed value.
22    ///
23    /// # Errors
24    ///
25    /// Returns a backend error whose source is the codec error when the stored
26    /// bytes are invalid.
27    fn decode_value(&self, bytes: &[u8]) -> Result<V, RedisBackendError>;
28}
29
30/// UTF-8 codec for `String` keys and values.
31#[derive(Clone, Copy, Debug, Default)]
32pub struct StringCodec;
33
34impl RedisCodec<String, String> for StringCodec {
35    fn encode_key(&self, key: &String) -> Result<Vec<u8>, RedisBackendError> {
36        Ok(key.as_bytes().to_vec())
37    }
38
39    fn encode_value(&self, value: &String) -> Result<Vec<u8>, RedisBackendError> {
40        Ok(value.as_bytes().to_vec())
41    }
42
43    fn decode_value(&self, bytes: &[u8]) -> Result<String, RedisBackendError> {
44        String::from_utf8(bytes.to_vec()).map_err(RedisBackendError::codec)
45    }
46}
47
48/// Identity codec for byte-vector keys and values.
49#[derive(Clone, Copy, Debug, Default)]
50pub struct BytesCodec;
51
52impl RedisCodec<Vec<u8>, Vec<u8>> for BytesCodec {
53    fn encode_key(&self, key: &Vec<u8>) -> Result<Vec<u8>, RedisBackendError> {
54        Ok(key.clone())
55    }
56
57    fn encode_value(&self, value: &Vec<u8>) -> Result<Vec<u8>, RedisBackendError> {
58        Ok(value.clone())
59    }
60
61    fn decode_value(&self, bytes: &[u8]) -> Result<Vec<u8>, RedisBackendError> {
62        Ok(bytes.to_vec())
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::{BytesCodec, RedisCodec};
69
70    #[test]
71    fn bytes_codec_round_trips_bytes() {
72        let codec = BytesCodec;
73        let bytes = vec![0, 1, 2, 255];
74        assert_eq!(codec.encode_key(&bytes).unwrap(), bytes);
75        assert_eq!(codec.encode_value(&bytes).unwrap(), bytes);
76        assert_eq!(codec.decode_value(&bytes).unwrap(), bytes);
77    }
78}