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
//! Misc utilities used by library

use std::fmt;
use std::io::{self, Write};

use percent_encoding::AsciiSet;

///Wrapper over `bytes::BytesMut` with convenient `io::Write` interface
///
///Automatically allocates instead of returning error.
pub struct BytesWriter {
    buf: bytes::BytesMut,
}

impl BytesWriter {
    #[inline]
    ///Creates new instance with provided capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            buf: bytes::BytesMut::with_capacity(capacity)
        }
    }

    #[inline]
    ///Converts to `bytes::Bytes`
    pub fn freeze(self) -> bytes::Bytes {
        self.buf.freeze()
    }
}

impl Default for BytesWriter {
    fn default() -> Self {
        Self::with_capacity(0)
    }
}

impl Into<bytes::Bytes> for BytesWriter {
    #[inline]
    fn into(self) -> bytes::Bytes {
        self.freeze()
    }
}

impl io::Write for BytesWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.buf.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        self.buf.extend_from_slice(buf);
        Ok(())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl fmt::Write for BytesWriter {
    fn write_str(&mut self, text: &str) -> fmt::Result {
        self.buf.extend_from_slice(text.as_bytes());
        Ok(())
    }
}

///Transforms `Display` into `HeaderValue`
pub fn display_to_header<T: fmt::Display>(data: &T) -> http::header::HeaderValue {
    let mut res = BytesWriter::default();
    let _ = write!(&mut res, "{}", data);
    unsafe { http::header::HeaderValue::from_shared_unchecked(res.freeze()) }
}

/// As defined in https://url.spec.whatwg.org/#fragment-percent-encode-set
pub const FRAGMENT_ENCODE_SET: &AsciiSet = &percent_encoding::CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');

/// As defined in https://url.spec.whatwg.org/#path-percent-encode-set
pub const PATH_ENCODE_SET: &AsciiSet = &FRAGMENT_ENCODE_SET.add(b'#').add(b'?').add(b'{').add(b'}');

/// As defined in https://url.spec.whatwg.org/#userinfo-percent-encode-set
pub const USER_INFO_ENCODE_SET: &AsciiSet = &PATH_ENCODE_SET.add(b'/').add(b':').add(b';').add(b'=').add(b'@').add(b'[').add(b'\\').add(b']').add(b'^').add(b'|');

/// As defined in https://tools.ietf.org/html/rfc5987#section-3.2.1
pub const HEADER_VALUE_ENCODE_SET: &AsciiSet = &percent_encoding::NON_ALPHANUMERIC.remove(b'!').remove(b'#').remove(b'$').remove(b'&').remove(b'+').remove(b'-').remove(b'.').remove(b'^').remove(b'_').remove(b'`').remove(b'|').remove(b'~');