tor_dirclient/
util.rs

1//! Helper functions for the directory client code
2
3use std::fmt::Write;
4
5/// Encode an HTTP request in a quick and dirty HTTP 1.0 format.
6pub(crate) fn encode_request(req: &http::Request<String>) -> String {
7    let mut s = format!("{} {} HTTP/1.0\r\n", req.method(), req.uri());
8
9    for (key, val) in req.headers().iter() {
10        write!(
11            s,
12            "{}: {}\r\n",
13            key,
14            val.to_str()
15                .expect("Added an HTTP header that wasn't UTF-8!")
16        )
17        .unwrap();
18    }
19
20    if req.method() == http::Method::POST || !req.body().is_empty() {
21        write!(s, "Content-Length: {}\r\n", req.body().len())
22            .expect("Added an HTTP header that wasn't UTF-8!");
23    }
24
25    s.push_str("\r\n");
26    s.push_str(req.body());
27
28    s
29}
30
31#[cfg(test)]
32mod test {
33    // @@ begin test lint list maintained by maint/add_warning @@
34    #![allow(clippy::bool_assert_comparison)]
35    #![allow(clippy::clone_on_copy)]
36    #![allow(clippy::dbg_macro)]
37    #![allow(clippy::mixed_attributes_style)]
38    #![allow(clippy::print_stderr)]
39    #![allow(clippy::print_stdout)]
40    #![allow(clippy::single_char_pattern)]
41    #![allow(clippy::unwrap_used)]
42    #![allow(clippy::unchecked_duration_subtraction)]
43    #![allow(clippy::useless_vec)]
44    #![allow(clippy::needless_pass_by_value)]
45    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
46    use super::*;
47
48    fn build_request(body: String, headers: &[(&str, &str)]) -> http::Request<String> {
49        let mut builder = http::Request::builder().method("GET").uri("/index.html");
50
51        for (name, value) in headers {
52            builder = builder.header(*name, *value);
53        }
54
55        builder.body(body).unwrap()
56    }
57
58    #[test]
59    fn format() {
60        fn chk_format(body: &str, content_length_expected: &str) {
61            let req = build_request(body.to_string(), &[]);
62
63            assert_eq!(
64                encode_request(&req),
65                format!("GET /index.html HTTP/1.0\r\n{content_length_expected}\r\n{body}")
66            );
67
68            let req = build_request(body.to_string(), &[("X-Marsupial", "Opossum")]);
69            assert_eq!(
70                encode_request(&req),
71                format!(
72                    "GET /index.html HTTP/1.0\r\nx-marsupial: Opossum\r\n{content_length_expected}\r\n{body}",
73                )
74            );
75        }
76
77        chk_format("", "");
78        chk_format("hello", "Content-Length: 5\r\n");
79    }
80}