Debian Codegraph @

third_party/rust/neqo-qpack/src/huffman.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![allow(
8 clippy::module_name_repetitions,
9 reason = "<https://github.com/mozilla/neqo/issues/2284#issuecomment-2782711813>"
10 )]
11
12 use crate::{
13 huffman_decode_helper::{huffman_decoder_root, HuffmanDecoderNode},
14 huffman_table::HUFFMAN_TABLE,
15 Error, Res,
16 };
17
18 struct BitReader<'a> {
19 input: &'a [u8],
20 offset: usize,
21 current_bit: u8,
22 }
23
24 impl<'a> BitReader<'a> {
25 pub const fn new(input: &'a [u8]) -> Self {
26 BitReader {
27 input,
28 offset: 0,
29 current_bit: 8,
30 }
31 }
32
33 pub fn read_bit(&mut self) -> Res<u8> {
34 if self.input.len() == self.offset {
35 return Err(Error::NeedMoreData);
36 }
37
38 if self.current_bit == 0 {
39 self.offset += 1;
40 if self.offset == self.input.len() {
41 return Err(Error::NeedMoreData);
42 }
43 self.current_bit = 8;
44 }
45 self.current_bit -= 1;
46 Ok((self.input[self.offset] >> self.current_bit) & 0x01)
47 }
48
49 pub fn verify_ending(&mut self, i: u8) -> Res<()> {
50 if (i + self.current_bit) > 7 {
51 return Err(Error::HuffmanDecompressionFailed);
52 }
53
54 if self.input.is_empty() {
55 Ok(())
56 } else if self.offset != self.input.len() {
57 Err(Error::HuffmanDecompressionFailed)
58 } else if self.input[self.input.len() - 1] & ((0x1 << (i + self.current_bit)) - 1)
59 == ((0x1 << (i + self.current_bit)) - 1)
60 {
61 self.current_bit = 0;
62 Ok(())
63 } else {
64 Err(Error::HuffmanDecompressionFailed)
65 }
66 }
67
68 pub const fn has_more_data(&self) -> bool {
69 !self.input.is_empty() && (self.offset != self.input.len() || (self.current_bit != 0))
70 }
71 }
72
73 /// Decodes huffman encoded input.
74 ///
75 /// # Errors
76 ///
77 /// This function may return `HuffmanDecompressionFailed` if `input` is not a correct
78 /// huffman-encoded array of bits.
79 ///
80 /// # Panics
81 ///
82 /// Never, but rust can't know that.
83 pub fn decode_huffman(input: &[u8]) -> Res<Vec<u8>> {
84 let mut reader = BitReader::new(input);
85 let mut output = Vec::new();
86 while reader.has_more_data() {
87 if let Some(c) = decode_character(&mut reader)? {
88 output.push(u8::try_from(c).map_err(|_| Error::HuffmanDecompressionFailed)?);
89 }
90 }
91
92 Ok(output)
93 }
94
95 fn decode_character(reader: &mut BitReader) -> Res<Option<u16>> {
96 let mut node: &HuffmanDecoderNode = huffman_decoder_root();
97 let mut i = 0;
98 while node.value.is_none() {
99 match reader.read_bit() {
100 Err(_) => {
101 reader.verify_ending(i)?;
102 return Ok(None);
103 }
104 Ok(b) => {
105 i += 1;
106 if let Some(next) = &node.next[usize::from(b)] {
107 node = next;
108 } else {
109 reader.verify_ending(i)?;
110 return Ok(None);
111 }
112 }
113 }
114 }
115 debug_assert!(node.value.is_some());
116 Ok(node.value)
117 }
118
119 /// # Panics
120 ///
121 /// Never, but rust doesn't know that.
122 #[must_use]
123 pub fn encode_huffman(input: &[u8]) -> Vec<u8> {
124 let mut output: Vec<u8> = Vec::new();
125 let mut left: u8 = 8;
126 let mut saved: u8 = 0;
127 for c in input {
128 let mut e = HUFFMAN_TABLE[*c as usize];
129
130 // Fill the previous byte
131 if e.len < left {
132 let b = (e.val & 0xFF) as u8; // Safe due to the mask.
133 saved |= b << (left - e.len);
134 left -= e.len;
135 e.len = 0;
136 } else {
137 let v: u8 = u8::try_from(e.val >> (e.len - left)).expect("fits into u8");
138 saved |= v;
139 output.push(saved);
140 e.len -= left;
141 left = 8;
142 saved = 0;
143 }
144
145 // Write full bytes
146 while e.len >= 8 {
147 let v: u8 = ((e.val >> (e.len - 8)) & 0xFF) as u8; // Safe due to the mask.
148 output.push(v);
149 e.len -= 8;
150 }
151
152 // Write the rest into saved.
153 if e.len > 0 {
154 saved = u8::try_from(e.val & ((1 << e.len) - 1)).expect("fits into u8") << (8 - e.len);
155 left = 8 - e.len;
156 }
157 }
158
159 if left < 8 {
160 let v: u8 = (1 << left) - 1;
161 saved |= v;
162 output.push(saved);
163 }
164
165 output
166 }
167
168 #[cfg(test)]
169 mod tests {
170 use super::{decode_huffman, encode_huffman, Error};
171
172 struct TestElement {
173 pub val: &'static [u8],
174 pub res: &'static [u8],
175 }
176 const TEST_CASES: &[TestElement] = &[
177 TestElement {
178 val: b"www.example.com",
179 res: &[
180 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff,
181 ],
182 },
183 TestElement {
184 val: b"no-cache",
185 res: &[0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xbf],
186 },
187 TestElement {
188 val: b"custom-key",
189 res: &[0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f],
190 },
191 TestElement {
192 val: b"custom-value",
193 res: &[0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf],
194 },
195 TestElement {
196 val: b"private",
197 res: &[0xae, 0xc3, 0x77, 0x1a, 0x4b],
198 },
199 TestElement {
200 val: b"Mon, 21 Oct 2013 20:13:21 GMT",
201 res: &[
202 0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b,
203 0x81, 0x66, 0xe0, 0x82, 0xa6, 0x2d, 0x1b, 0xff,
204 ],
205 },
206 TestElement {
207 val: b"https://www.example.com",
208 res: &[
209 0x9d, 0x29, 0xad, 0x17, 0x18, 0x63, 0xc7, 0x8f, 0x0b, 0x97, 0xc8, 0xe9, 0xae, 0x82,
210 0xae, 0x43, 0xd3,
211 ],
212 },
213 TestElement {
214 val: b"Mon, 21 Oct 2013 20:13:22 GMT",
215 res: &[
216 0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b,
217 0x81, 0x66, 0xe0, 0x84, 0xa6, 0x2d, 0x1b, 0xff,
218 ],
219 },
220 TestElement {
221 val: b"gzip",
222 res: &[0x9b, 0xd9, 0xab],
223 },
224 TestElement {
225 val: b"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1",
226 res: &[
227 0x94, 0xe7, 0x82, 0x1d, 0xd7, 0xf2, 0xe6, 0xc7, 0xb3, 0x35, 0xdf, 0xdf, 0xcd, 0x5b,
228 0x39, 0x60, 0xd5, 0xaf, 0x27, 0x08, 0x7f, 0x36, 0x72, 0xc1, 0xab, 0x27, 0x0f, 0xb5,
229 0x29, 0x1f, 0x95, 0x87, 0x31, 0x60, 0x65, 0xc0, 0x03, 0xed, 0x4e, 0xe5, 0xb1, 0x06,
230 0x3d, 0x50, 0x07,
231 ],
232 },
233 TestElement {
234 val: b"<?\\ >",
235 res: &[0xff, 0xf9, 0xfe, 0x7f, 0xff, 0x05, 0x3f, 0xef],
236 },
237 ];
238
239 const WRONG_END: &[u8] = &[0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xaf];
240
241 #[test]
242 fn encoder() {
243 for e in TEST_CASES {
244 let out = encode_huffman(e.val);
245 assert_eq!(out[..], *e.res);
246 }
247 }
248
249 #[test]
250 fn decoder() {
251 for e in TEST_CASES {
252 let res = decode_huffman(e.res);
253 assert!(res.is_ok());
254 assert_eq!(res.unwrap()[..], *e.val);
255 }
256 }
257
258 #[test]
259 fn decoder_error_wrong_ending() {
260 assert_eq!(
261 decode_huffman(WRONG_END),
262 Err(Error::HuffmanDecompressionFailed)
263 );
264 }
265 }