1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use bytes::Bytes;
use serde::{Deserialize, Serialize};

/// Body struct
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
pub struct Body(Vec<u8>);

impl From<String> for Body {
    fn from(s: String) -> Body {
        Body(s.into())
    }
}

impl From<&str> for Body {
    fn from(s: &str) -> Body {
        Body(s.into())
    }
}

impl From<Bytes> for Body {
    fn from(b: Bytes) -> Body {
        Body(b.into())
    }
}

impl From<Vec<u8>> for Body {
    fn from(v: Vec<u8>) -> Body {
        Body(v)
    }
}

impl From<&[u8]> for Body {
    fn from(slice: &[u8]) -> Body {
        Body(slice.into())
    }
}

impl From<()> for Body {
    fn from(_: ()) -> Body {
        Body::empty()
    }
}

impl From<HttpResponse> for Body {
    fn from(res: HttpResponse) -> Self {
        res.body.into()
    }
}

impl From<Body> for Bytes {
    fn from(body: Body) -> Bytes {
        Bytes::from(body.0)
    }
}

impl TryInto<String> for Body {
    type Error = FromUtf8Error;

    fn try_into(self) -> Result<String, Self::Error> {
        String::from_utf8(self.0)
    }
}

impl Body {
    /// empty body
    pub fn empty() -> Body {
        Body(vec![])
    }

    /// length of body
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// tells whether body is empty
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// retrieve body
    pub fn inner(self) -> Vec<u8> {
        self.0
    }

    /// create a json body
    pub fn json<T: Serialize>(data: T) -> crate::Result<Body> {
        match serde_json::to_string(&data) {
            Ok(r) => Ok(Body(r.into())),
            Err(_e) => Err(crate::Error::new(
                crate::error::Kind::Request,
                Some("".to_string()),
            )),
        }
    }

    /// create a regular text body
    pub fn text<T: Into<Vec<u8>>>(data: T) -> crate::Result<Body> {
        Ok(Body(data.into()))
    }
}

impl Read for Body {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        Cursor::new(self.0.clone()).read(buf)
    }
}

use std::{
    convert::TryInto,
    io::{Cursor, Read},
    string::FromUtf8Error,
};

use crate::HttpResponse;