Coverage Report

Created: 2024-02-20 21:15

/builds/xfbs/cindy/common/src/api/encoding.rs
Line
Count
Source (jump to first uncovered line)
1
use bytes::Bytes;
2
pub use restless::data::*;
3
use serde::{de::DeserializeOwned, Serialize};
4
use std::{convert::Infallible, error::Error};
5
6
pub trait ResponseEncoding: Sized {
7
    type Target;
8
    type Error: Error + Sync + Send + 'static;
9
10
    fn decode(data: Bytes) -> Result<Self::Target, Self::Error>;
11
}
12
13
impl<T: DeserializeOwned> ResponseEncoding for Json<T> {
14
    type Target = T;
15
    type Error = serde_json::Error;
16
17
0
    fn decode(data: Bytes) -> Result<Self::Target, Self::Error> {
18
0
        serde_json::from_slice(&data[..])
19
0
    }
20
}
21
22
impl ResponseEncoding for Bytes {
23
    type Target = Bytes;
24
    type Error = Infallible;
25
26
0
    fn decode(data: Bytes) -> Result<Self::Target, Self::Error> {
27
0
        Ok(data)
28
0
    }
29
}
30
31
impl ResponseEncoding for () {
32
    type Target = ();
33
    type Error = Infallible;
34
35
0
    fn decode(_data: Bytes) -> Result<Self::Target, Self::Error> {
36
0
        // TODO: raise error on non empty body?
37
0
        Ok(())
38
0
    }
39
}
40
41
pub trait RequestEncoding {
42
    fn encode(&self) -> Bytes;
43
}
44
45
impl RequestEncoding for () {
46
0
    fn encode(&self) -> Bytes {
47
0
        Vec::new().into()
48
0
    }
49
}
50
51
impl RequestEncoding for Bytes {
52
0
    fn encode(&self) -> Bytes {
53
0
        self.clone()
54
0
    }
55
}
56
57
impl<T: Serialize> RequestEncoding for Json<T> {
58
0
    fn encode(&self) -> Bytes {
59
0
        serde_json::to_vec(&self.0).unwrap().into()
60
0
    }
61
}