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