Skip to main content

twilight_http/request/
multipart.rs

1#[derive(Clone, Debug)]
2#[must_use = "has no effect if not built into a Form"]
3pub struct Form {
4    boundary: [u8; 15],
5    buffer: Vec<u8>,
6}
7
8impl Form {
9    const APPLICATION_JSON: &'static [u8; 16] = b"application/json";
10
11    const BOUNDARY_TERMINATOR: &'static [u8; 2] = b"--";
12    const CONTENT_DISPOSITION_1: &'static [u8; 38] = b"Content-Disposition: form-data; name=\"";
13    const CONTENT_DISPOSITION_2: &'static [u8; 13] = b"\"; filename=\"";
14    const CONTENT_DISPOSITION_3: &'static [u8; 1] = b"\"";
15    const CONTENT_TYPE: &'static [u8; 14] = b"Content-Type: ";
16    const NEWLINE: &'static [u8; 2] = b"\r\n";
17
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    pub(crate) const fn from_parts(boundary: [u8; 15], buffer: Vec<u8>) -> Self {
23        Self { boundary, buffer }
24    }
25
26    /// Consume the form, returning the buffer's contents.
27    pub fn build(mut self) -> Vec<u8> {
28        self.buffer.extend(Self::BOUNDARY_TERMINATOR);
29
30        self.buffer
31    }
32
33    /// Get the form's appropriate content type for requests.
34    pub fn content_type(&self) -> Vec<u8> {
35        const NAME: &str = "multipart/form-data; boundary=";
36
37        let mut content_type = Vec::with_capacity(NAME.len() + self.boundary.len());
38        content_type.extend(NAME.as_bytes());
39        content_type.extend(self.boundary);
40
41        content_type
42    }
43
44    pub fn part(mut self, name: &[u8], value: &[u8]) -> Self {
45        // Write the Content-Disposition header.
46        self.buffer.extend(Self::NEWLINE);
47        self.buffer.extend(Self::CONTENT_DISPOSITION_1);
48        self.buffer.extend(name);
49        self.buffer.extend(Self::CONTENT_DISPOSITION_3);
50        self.buffer.extend(Self::NEWLINE);
51
52        // Write a newline between the headers and the value, the value
53        // itself, a newline, and finally the boundary.
54        self.buffer.extend(Self::NEWLINE);
55        self.buffer.extend(value);
56        self.buffer.extend(Self::NEWLINE);
57        self.buffer.extend(Self::BOUNDARY_TERMINATOR);
58        self.buffer.extend(self.boundary);
59
60        self
61    }
62
63    pub fn file_part(mut self, name: &[u8], filename: &[u8], value: &[u8]) -> Self {
64        // Write the Content-Disposition header.
65        self.buffer.extend(Self::NEWLINE);
66        self.buffer.extend(Self::CONTENT_DISPOSITION_1);
67        self.buffer.extend(name);
68        self.buffer.extend(Self::CONTENT_DISPOSITION_2);
69        self.buffer.extend(filename);
70        self.buffer.extend(Self::CONTENT_DISPOSITION_3);
71        self.buffer.extend(Self::NEWLINE);
72
73        // Write a newline between the headers and the value, the value
74        // itself, a newline, and finally the boundary.
75        self.buffer.extend(Self::NEWLINE);
76        self.buffer.extend(value);
77        self.buffer.extend(Self::NEWLINE);
78        self.buffer.extend(Self::BOUNDARY_TERMINATOR);
79        self.buffer.extend(self.boundary);
80
81        self
82    }
83
84    /// Preview the built buffer's length without consuming the form.
85    #[allow(clippy::len_without_is_empty)]
86    pub const fn len(&self) -> usize {
87        self.buffer.len() + Self::BOUNDARY_TERMINATOR.len()
88    }
89
90    pub fn json_part(mut self, name: &[u8], value: &[u8]) -> Self {
91        // Write the Content-Disposition header.
92        self.buffer.extend(Self::NEWLINE);
93        self.buffer.extend(Self::CONTENT_DISPOSITION_1);
94        self.buffer.extend(name);
95        self.buffer.extend(Self::CONTENT_DISPOSITION_3);
96        self.buffer.extend(Self::NEWLINE);
97
98        // If there is a Content-Type, write its key, itself, and a newline.
99        self.buffer.extend(Self::CONTENT_TYPE);
100        self.buffer.extend(Self::APPLICATION_JSON);
101        self.buffer.extend(Self::NEWLINE);
102
103        // Write a newline between the headers and the value, the value
104        // itself, a newline, and finally the boundary.
105        self.buffer.extend(Self::NEWLINE);
106        self.buffer.extend(value);
107        self.buffer.extend(Self::NEWLINE);
108        self.buffer.extend(Self::BOUNDARY_TERMINATOR);
109        self.buffer.extend(self.boundary);
110
111        self
112    }
113
114    pub fn into_parts(self) -> ([u8; 15], Vec<u8>) {
115        (self.boundary, self.buffer)
116    }
117}
118
119impl Default for Form {
120    fn default() -> Self {
121        let mut form = Self {
122            boundary: random_boundary(),
123            buffer: Vec::new(),
124        };
125
126        // Write the first boundary.
127        form.buffer.extend(Self::BOUNDARY_TERMINATOR);
128        form.buffer.extend(form.boundary);
129
130        form
131    }
132}
133
134/// Generate a random boundary that is 15 characters long.
135pub fn random_boundary() -> [u8; 15] {
136    let mut boundary = [0; 15];
137
138    for value in &mut boundary {
139        *value = fastrand::alphanumeric() as u8;
140    }
141
142    boundary
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148    use std::str;
149
150    #[test]
151    fn form_builder() {
152        let form = Form::new()
153            .json_part(b"payload_json", b"json_value")
154            .file_part(b"files[0]", b"filename.jpg", b"file_value");
155
156        let boundary = str::from_utf8(&form.boundary).unwrap();
157        let expected = format!(
158            "--{boundary}\r\n\
159        Content-Disposition: form-data; name=\"payload_json\"\r\n\
160        Content-Type: application/json\r\n\
161        \r\n\
162        json_value\r\n\
163        --{boundary}\r\n\
164        Content-Disposition: form-data; name=\"files[0]\"; filename=\"filename.jpg\"\r\n\
165        \r\n\
166        file_value\r\n\
167        --{boundary}--",
168        );
169
170        let buffer_len = form.len();
171        let buffer = form.build();
172
173        assert_eq!(expected.as_bytes(), buffer);
174        assert_eq!(buffer_len, buffer.len());
175    }
176}