apalis_core/codec/
json.rs

1use std::marker::PhantomData;
2
3use crate::codec::Codec;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7/// Json encoding and decoding
8#[derive(Debug, Clone, Default)]
9pub struct JsonCodec<Output> {
10    _o: PhantomData<Output>,
11}
12
13impl Codec for JsonCodec<Vec<u8>> {
14    type Compact = Vec<u8>;
15    type Error = serde_json::Error;
16    fn encode<T: Serialize>(input: T) -> Result<Vec<u8>, Self::Error> {
17        serde_json::to_vec(&input)
18    }
19
20    fn decode<O>(compact: Vec<u8>) -> Result<O, Self::Error>
21    where
22        O: for<'de> Deserialize<'de>,
23    {
24        serde_json::from_slice(&compact)
25    }
26}
27
28impl Codec for JsonCodec<String> {
29    type Compact = String;
30    type Error = serde_json::Error;
31    fn encode<T: Serialize>(input: T) -> Result<String, Self::Error> {
32        serde_json::to_string(&input)
33    }
34
35    fn decode<O>(compact: String) -> Result<O, Self::Error>
36    where
37        O: for<'de> Deserialize<'de>,
38    {
39        serde_json::from_str(&compact)
40    }
41}
42
43impl Codec for JsonCodec<Value> {
44    type Compact = Value;
45    type Error = serde_json::Error;
46    fn encode<T: Serialize>(input: T) -> Result<Value, Self::Error> {
47        serde_json::to_value(input)
48    }
49
50    fn decode<O>(compact: Value) -> Result<O, Self::Error>
51    where
52        O: for<'de> Deserialize<'de>,
53    {
54        serde_json::from_value(compact)
55    }
56}