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
use std::fs::File;
use std::io::{self, Read};

/// A HTTP request body.
///
/// This is either a file pointer or a memory sequence of bytes.
/// This distinction only matters when using `DirectClient`, in which case a file
/// might be read chunked.
///
/// Note that this is **not** the same type as the one found in the `reqwest` crate.
#[derive(Debug)]
pub struct Body {
    value: BodyValue,
}

#[derive(Debug)]
enum BodyValue {
    /// Bytes kept in memory.
    Bytes(Vec<u8>),

    /// A pointer to a file yet to be read.
    File(File),
}

impl Body {
    // TODO: Consider whether this should be public for everyone.
    pub(crate) fn try_to_vec(self) -> Result<Vec<u8>, io::Error> {
        match self.value {
            BodyValue::Bytes(bs) => Ok(bs),
            BodyValue::File(mut f) => {
                let mut bytes = Vec::new();
                f.read_to_end(&mut bytes)?;
                Ok(bytes)
            }
        }
    }
}

impl From<Body> for ::reqwest::blocking::Body {
    fn from(b: Body) -> ::reqwest::blocking::Body {
        match b.value {
            BodyValue::Bytes(b) => b.into(),
            BodyValue::File(f) => f.into(),
        }
    }
}

impl From<Vec<u8>> for Body {
    #[inline]
    fn from(v: Vec<u8>) -> Self {
        Body {
            value: BodyValue::Bytes(v.into()),
        }
    }
}

impl From<String> for Body {
    #[inline]
    fn from(s: String) -> Self {
        Body {
            value: BodyValue::Bytes(s.into()),
        }
    }
}

impl<'a> From<&'a str> for Body {
    #[inline]
    fn from(s: &'a str) -> Self {
        Body {
            value: BodyValue::Bytes(s.into()),
        }
    }
}

impl From<&'static [u8]> for Body {
    #[inline]
    fn from(s: &'static [u8]) -> Self {
        Body {
            value: BodyValue::Bytes(s.into()),
        }
    }
}

impl From<File> for Body {
    #[inline]
    fn from(f: File) -> Self {
        Body {
            value: BodyValue::File(f),
        }
    }
}