monoio_http/h2/frame/
util.rs

1use std::fmt;
2
3use bytes::Bytes;
4
5use super::Error;
6
7/// Strip padding from the given payload.
8///
9/// It is assumed that the frame had the padded flag set. This means that the
10/// first byte is the length of the padding with that many
11/// 0 bytes expected to follow the actual payload.
12///
13/// # Returns
14///
15/// A slice of the given payload where the actual one is found and the length
16/// of the padding.
17///
18/// If the padded payload is invalid (e.g. the length of the padding is equal
19/// to the total length), returns `None`.
20pub fn strip_padding(payload: &mut Bytes) -> Result<u8, Error> {
21    let payload_len = payload.len();
22    if payload_len == 0 {
23        // If this is the case, the frame is invalid as no padding length can be
24        // extracted, even though the frame should be padded.
25        return Err(Error::TooMuchPadding);
26    }
27
28    let pad_len = payload[0] as usize;
29
30    if pad_len >= payload_len {
31        // This is invalid: the padding length MUST be less than the
32        // total frame size.
33        return Err(Error::TooMuchPadding);
34    }
35
36    let _ = payload.split_to(1);
37    let _ = payload.split_off(payload_len - pad_len - 1);
38
39    Ok(pad_len as u8)
40}
41
42pub(super) fn debug_flags<'a, 'f: 'a>(
43    fmt: &'a mut fmt::Formatter<'f>,
44    bits: u8,
45) -> DebugFlags<'a, 'f> {
46    let result = write!(fmt, "({:#x}", bits);
47    DebugFlags {
48        fmt,
49        result,
50        started: false,
51    }
52}
53
54pub(super) struct DebugFlags<'a, 'f: 'a> {
55    fmt: &'a mut fmt::Formatter<'f>,
56    result: fmt::Result,
57    started: bool,
58}
59
60impl<'a, 'f: 'a> DebugFlags<'a, 'f> {
61    pub(super) fn flag_if(&mut self, enabled: bool, name: &str) -> &mut Self {
62        if enabled {
63            self.result = self.result.and_then(|()| {
64                let prefix = if self.started {
65                    " | "
66                } else {
67                    self.started = true;
68                    ": "
69                };
70
71                write!(self.fmt, "{}{}", prefix, name)
72            });
73        }
74        self
75    }
76
77    pub(super) fn finish(&mut self) -> fmt::Result {
78        self.result.and_then(|()| write!(self.fmt, ")"))
79    }
80}