crux_http/
expect.rs

1use std::marker::PhantomData;
2
3use http_types::convert::DeserializeOwned;
4
5use crate::{Response, Result};
6
7pub trait ResponseExpectation {
8    type Body;
9
10    fn decode(&self, resp: crate::Response<Vec<u8>>) -> Result<Response<Self::Body>>;
11}
12
13pub struct ExpectBytes;
14
15impl ResponseExpectation for ExpectBytes {
16    type Body = Vec<u8>;
17
18    fn decode(&self, resp: crate::Response<Vec<u8>>) -> Result<Response<Vec<u8>>> {
19        Ok(resp)
20    }
21}
22
23#[derive(Default)]
24pub struct ExpectString;
25
26impl ResponseExpectation for ExpectString {
27    type Body = String;
28
29    fn decode(&self, mut resp: crate::Response<Vec<u8>>) -> Result<Response<String>> {
30        let body = resp.body_string()?;
31        Ok(resp.with_body(body))
32    }
33}
34
35pub struct ExpectJson<T> {
36    phantom: PhantomData<fn() -> T>,
37}
38
39impl<T> Default for ExpectJson<T> {
40    fn default() -> Self {
41        Self {
42            phantom: Default::default(),
43        }
44    }
45}
46
47impl<T> ResponseExpectation for ExpectJson<T>
48where
49    T: DeserializeOwned,
50{
51    type Body = T;
52
53    fn decode(&self, mut resp: crate::Response<Vec<u8>>) -> Result<Response<T>> {
54        let body = resp.body_json::<T>()?;
55        Ok(resp.with_body(body))
56    }
57}