miku_hyper/ext/
mod.rs

1//! HTTP extensions.
2
3#[cfg(all(any(feature = "client", feature = "server"), feature = "http1"))]
4use bytes::Bytes;
5#[cfg(any(
6    all(any(feature = "client", feature = "server"), feature = "http1"),
7    feature = "ffi"
8))]
9use http::header::HeaderName;
10#[cfg(all(any(feature = "client", feature = "server"), feature = "http1"))]
11use http::header::{HeaderMap, IntoHeaderName, ValueIter};
12#[cfg(feature = "ffi")]
13use std::collections::HashMap;
14#[cfg(feature = "http2")]
15use std::fmt;
16
17#[cfg(any(feature = "http1", feature = "ffi"))]
18mod h1_reason_phrase;
19#[cfg(any(feature = "http1", feature = "ffi"))]
20pub use h1_reason_phrase::ReasonPhrase;
21
22#[cfg(feature = "http2")]
23/// Represents the `:protocol` pseudo-header used by
24/// the [Extended CONNECT Protocol].
25///
26/// [Extended CONNECT Protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
27#[derive(Clone, Eq, PartialEq)]
28pub struct Protocol {
29    inner: h2::ext::Protocol,
30}
31
32#[cfg(feature = "http2")]
33impl Protocol {
34    /// Converts a static string to a protocol name.
35    pub const fn from_static(value: &'static str) -> Self {
36        Self {
37            inner: h2::ext::Protocol::from_static(value),
38        }
39    }
40
41    /// Returns a str representation of the header.
42    pub fn as_str(&self) -> &str {
43        self.inner.as_str()
44    }
45
46    #[cfg(feature = "server")]
47    pub(crate) fn from_inner(inner: h2::ext::Protocol) -> Self {
48        Self { inner }
49    }
50
51    #[cfg(all(feature = "client", feature = "http2"))]
52    pub(crate) fn into_inner(self) -> h2::ext::Protocol {
53        self.inner
54    }
55}
56
57#[cfg(feature = "http2")]
58impl<'a> From<&'a str> for Protocol {
59    fn from(value: &'a str) -> Self {
60        Self {
61            inner: h2::ext::Protocol::from(value),
62        }
63    }
64}
65
66#[cfg(feature = "http2")]
67impl AsRef<[u8]> for Protocol {
68    fn as_ref(&self) -> &[u8] {
69        self.inner.as_ref()
70    }
71}
72
73#[cfg(feature = "http2")]
74impl fmt::Debug for Protocol {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        self.inner.fmt(f)
77    }
78}
79
80#[cfg(feature = "http2")]
81pub use h2::{
82    ext::PseudoType,
83    frame::{Priority as FramePriority, StreamDependency as FrameStreamDependency},
84};
85
86/// A map from header names to their original casing as received in an HTTP message.
87///
88/// If an HTTP/1 response `res` is parsed on a connection whose option
89/// [`preserve_header_case`] was set to true and the response included
90/// the following headers:
91///
92/// ```ignore
93/// x-Bread: Baguette
94/// X-BREAD: Pain
95/// x-bread: Ficelle
96/// ```
97///
98/// Then `res.extensions().get::<HeaderCaseMap>()` will return a map with:
99///
100/// ```ignore
101/// HeaderCaseMap({
102///     "x-bread": ["x-Bread", "X-BREAD", "x-bread"],
103/// })
104/// ```
105///
106/// [`preserve_header_case`]: /client/struct.Client.html#method.preserve_header_case
107#[cfg(all(any(feature = "client", feature = "server"), feature = "http1"))]
108#[derive(Clone, Debug)]
109pub(crate) struct HeaderCaseMap(HeaderMap<Bytes>);
110
111#[cfg(all(any(feature = "client", feature = "server"), feature = "http1"))]
112impl HeaderCaseMap {
113    /// Returns a view of all spellings associated with that header name,
114    /// in the order they were found.
115    #[cfg(feature = "client")]
116    pub(crate) fn get_all<'a>(
117        &'a self,
118        name: &HeaderName,
119    ) -> impl Iterator<Item = impl AsRef<[u8]> + 'a> + 'a {
120        self.get_all_internal(name)
121    }
122
123    /// Returns a view of all spellings associated with that header name,
124    /// in the order they were found.
125    #[cfg(any(feature = "client", feature = "server"))]
126    pub(crate) fn get_all_internal(&self, name: &HeaderName) -> ValueIter<'_, Bytes> {
127        self.0.get_all(name).into_iter()
128    }
129
130    #[cfg(any(feature = "client", feature = "server"))]
131    pub(crate) fn default() -> Self {
132        Self(Default::default())
133    }
134
135    #[cfg(any(test, feature = "ffi"))]
136    pub(crate) fn insert(&mut self, name: HeaderName, orig: Bytes) {
137        self.0.insert(name, orig);
138    }
139
140    #[cfg(any(feature = "client", feature = "server"))]
141    pub(crate) fn append<N>(&mut self, name: N, orig: Bytes)
142    where
143        N: IntoHeaderName,
144    {
145        self.0.append(name, orig);
146    }
147}
148
149#[cfg(feature = "ffi")]
150#[derive(Clone, Debug)]
151/// Hashmap<Headername, numheaders with that name>
152pub(crate) struct OriginalHeaderOrder {
153    /// Stores how many entries a Headername maps to. This is used
154    /// for accounting.
155    num_entries: HashMap<HeaderName, usize>,
156    /// Stores the ordering of the headers. ex: `vec[i] = (headerName, idx)`,
157    /// The vector is ordered such that the ith element
158    /// represents the ith header that came in off the line.
159    /// The `HeaderName` and `idx` are then used elsewhere to index into
160    /// the multi map that stores the header values.
161    entry_order: Vec<(HeaderName, usize)>,
162}
163
164#[cfg(all(feature = "http1", feature = "ffi"))]
165impl OriginalHeaderOrder {
166    pub(crate) fn default() -> Self {
167        OriginalHeaderOrder {
168            num_entries: HashMap::new(),
169            entry_order: Vec::new(),
170        }
171    }
172
173    pub(crate) fn insert(&mut self, name: HeaderName) {
174        if !self.num_entries.contains_key(&name) {
175            let idx = 0;
176            self.num_entries.insert(name.clone(), 1);
177            self.entry_order.push((name, idx));
178        }
179        // Replacing an already existing element does not
180        // change ordering, so we only care if its the first
181        // header name encountered
182    }
183
184    pub(crate) fn append<N>(&mut self, name: N)
185    where
186        N: IntoHeaderName + Into<HeaderName> + Clone,
187    {
188        let name: HeaderName = name.into();
189        let idx;
190        if self.num_entries.contains_key(&name) {
191            idx = self.num_entries[&name];
192            *self.num_entries.get_mut(&name).unwrap() += 1;
193        } else {
194            idx = 0;
195            self.num_entries.insert(name.clone(), 1);
196        }
197        self.entry_order.push((name, idx));
198    }
199
200    // No doc test is run here because `RUSTFLAGS='--cfg hyper_unstable_ffi'`
201    // is needed to compile. Once ffi is stabilized `no_run` should be removed
202    // here.
203    /// This returns an iterator that provides header names and indexes
204    /// in the original order received.
205    ///
206    /// # Examples
207    /// ```no_run
208    /// use miku_hyper::ext::OriginalHeaderOrder;
209    /// use miku_hyper::header::{HeaderName, HeaderValue, HeaderMap};
210    ///
211    /// let mut h_order = OriginalHeaderOrder::default();
212    /// let mut h_map = Headermap::new();
213    ///
214    /// let name1 = b"Set-CookiE";
215    /// let value1 = b"a=b";
216    /// h_map.append(name1);
217    /// h_order.append(name1);
218    ///
219    /// let name2 = b"Content-Encoding";
220    /// let value2 = b"gzip";
221    /// h_map.append(name2, value2);
222    /// h_order.append(name2);
223    ///
224    /// let name3 = b"SET-COOKIE";
225    /// let value3 = b"c=d";
226    /// h_map.append(name3, value3);
227    /// h_order.append(name3)
228    ///
229    /// let mut iter = h_order.get_in_order()
230    ///
231    /// let (name, idx) = iter.next();
232    /// assert_eq!(b"a=b", h_map.get_all(name).nth(idx).unwrap());
233    ///
234    /// let (name, idx) = iter.next();
235    /// assert_eq!(b"gzip", h_map.get_all(name).nth(idx).unwrap());
236    ///
237    /// let (name, idx) = iter.next();
238    /// assert_eq!(b"c=d", h_map.get_all(name).nth(idx).unwrap());
239    /// ```
240    pub(crate) fn get_in_order(&self) -> impl Iterator<Item = &(HeaderName, usize)> {
241        self.entry_order.iter()
242    }
243}