Debian Codegraph @

third_party/rust/neqo-qpack/src/encoder_instructions.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 use std::{
8 fmt::{self, Display, Formatter},
9 mem,
10 };
11
12 use neqo_common::{qdebug, qtrace};
13
14 use crate::{
15 prefix::{
16 ENCODER_CAPACITY, ENCODER_DUPLICATE, ENCODER_INSERT_WITH_NAME_LITERAL,
17 ENCODER_INSERT_WITH_NAME_REF_DYNAMIC, ENCODER_INSERT_WITH_NAME_REF_STATIC, NO_PREFIX,
18 },
19 qpack_send_buf::QpackData,
20 reader::{IntReader, LiteralReader, ReadByte, Reader},
21 Res,
22 };
23
24 // The encoder only uses InsertWithNameLiteral.
25 // All instructions are used for testing, therefore they are guarded with `#[cfg(test)]`.
26 #[derive(Debug, PartialEq, Eq)]
27 pub enum EncoderInstruction<'a> {
28 Capacity {
29 value: u64,
30 },
31 #[cfg(test)]
32 InsertWithNameRefStatic {
33 index: u64,
34 value: &'a [u8],
35 },
36 #[cfg(test)]
37 InsertWithNameRefDynamic {
38 index: u64,
39 value: &'a [u8],
40 },
41 InsertWithNameLiteral {
42 name: &'a [u8],
43 value: &'a [u8],
44 },
45 #[cfg(test)]
46 Duplicate {
47 index: u64,
48 },
49 #[cfg(test)]
50 #[expect(dead_code, reason = "Only used in tests.")]
51 NoInstruction,
52 }
53
54 impl EncoderInstruction<'_> {
55 pub(crate) fn marshal(&self, enc: &mut QpackData, use_huffman: bool) {
56 match self {
57 Self::Capacity { value } => {
58 enc.encode_prefixed_encoded_int(ENCODER_CAPACITY, *value);
59 }
60 #[cfg(test)]
61 Self::InsertWithNameRefStatic { index, value } => {
62 enc.encode_prefixed_encoded_int(ENCODER_INSERT_WITH_NAME_REF_STATIC, *index);
63 enc.encode_literal(use_huffman, NO_PREFIX, value);
64 }
65 #[cfg(test)]
66 Self::InsertWithNameRefDynamic { index, value } => {
67 enc.encode_prefixed_encoded_int(ENCODER_INSERT_WITH_NAME_REF_DYNAMIC, *index);
68 enc.encode_literal(use_huffman, NO_PREFIX, value);
69 }
70 Self::InsertWithNameLiteral { name, value } => {
71 enc.encode_literal(use_huffman, ENCODER_INSERT_WITH_NAME_LITERAL, name);
72 enc.encode_literal(use_huffman, NO_PREFIX, value);
73 }
74 #[cfg(test)]
75 Self::Duplicate { index } => {
76 enc.encode_prefixed_encoded_int(ENCODER_DUPLICATE, *index);
77 }
78 #[cfg(test)]
79 Self::NoInstruction => {}
80 }
81 }
82 }
83
84 #[derive(Debug)]
85 enum EncoderInstructionReaderState {
86 ReadInstruction,
87 ReadFirstInt { reader: IntReader },
88 ReadFirstLiteral { reader: LiteralReader },
89 ReadSecondLiteral { reader: LiteralReader },
90 Done,
91 }
92
93 #[derive(Debug, PartialEq, Eq)]
94 pub enum DecodedEncoderInstruction {
95 Capacity { value: u64 },
96 InsertWithNameRefStatic { index: u64, value: Vec<u8> },
97 InsertWithNameRefDynamic { index: u64, value: Vec<u8> },
98 InsertWithNameLiteral { name: Vec<u8>, value: Vec<u8> },
99 Duplicate { index: u64 },
100 NoInstruction,
101 }
102
103 impl<'a> From<&'a EncoderInstruction<'a>> for DecodedEncoderInstruction {
104 fn from(inst: &'a EncoderInstruction) -> Self {
105 match inst {
106 EncoderInstruction::Capacity { value } => Self::Capacity { value: *value },
107 #[cfg(test)]
108 EncoderInstruction::InsertWithNameRefStatic { index, value } => {
109 Self::InsertWithNameRefStatic {
110 index: *index,
111 value: value.to_vec(),
112 }
113 }
114 #[cfg(test)]
115 EncoderInstruction::InsertWithNameRefDynamic { index, value } => {
116 Self::InsertWithNameRefDynamic {
117 index: *index,
118 value: value.to_vec(),
119 }
120 }
121 EncoderInstruction::InsertWithNameLiteral { name, value } => {
122 Self::InsertWithNameLiteral {
123 name: name.to_vec(),
124 value: value.to_vec(),
125 }
126 }
127 #[cfg(test)]
128 EncoderInstruction::Duplicate { index } => Self::Duplicate { index: *index },
129 #[cfg(test)]
130 EncoderInstruction::NoInstruction => Self::NoInstruction,
131 }
132 }
133 }
134
135 #[derive(Debug)]
136 pub struct EncoderInstructionReader {
137 state: EncoderInstructionReaderState,
138 instruction: DecodedEncoderInstruction,
139 }
140
141 impl Display for EncoderInstructionReader {
142 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
143 write!(
144 f,
145 "EncoderInstructionReader state={:?} instruction:{:?}",
146 self.state, self.instruction
147 )
148 }
149 }
150
151 impl EncoderInstructionReader {
152 pub const fn new() -> Self {
153 Self {
154 state: EncoderInstructionReaderState::ReadInstruction,
155 instruction: DecodedEncoderInstruction::NoInstruction,
156 }
157 }
158
159 fn decode_instruction_from_byte(&mut self, b: u8) {
160 self.instruction = if ENCODER_INSERT_WITH_NAME_REF_STATIC.cmp_prefix(b) {
161 DecodedEncoderInstruction::InsertWithNameRefStatic {
162 index: 0,
163 value: Vec::new(),
164 }
165 } else if ENCODER_INSERT_WITH_NAME_REF_DYNAMIC.cmp_prefix(b) {
166 DecodedEncoderInstruction::InsertWithNameRefDynamic {
167 index: 0,
168 value: Vec::new(),
169 }
170 } else if ENCODER_INSERT_WITH_NAME_LITERAL.cmp_prefix(b) {
171 DecodedEncoderInstruction::InsertWithNameLiteral {
172 name: Vec::new(),
173 value: Vec::new(),
174 }
175 } else if ENCODER_CAPACITY.cmp_prefix(b) {
176 DecodedEncoderInstruction::Capacity { value: 0 }
177 } else if ENCODER_DUPLICATE.cmp_prefix(b) {
178 DecodedEncoderInstruction::Duplicate { index: 0 }
179 } else {
180 unreachable!("The above patterns match everything");
181 };
182 qdebug!("[{self}] instruction decoded");
183 }
184
185 fn decode_instruction_type<T: ReadByte + Reader>(&mut self, recv: &mut T) -> Res<()> {
186 let b = recv.read_byte()?;
187
188 self.decode_instruction_from_byte(b);
189 match self.instruction {
190 DecodedEncoderInstruction::Capacity { .. }
191 | DecodedEncoderInstruction::Duplicate { .. } => {
192 self.state = EncoderInstructionReaderState::ReadFirstInt {
193 reader: IntReader::new(b, ENCODER_CAPACITY.len()),
194 }
195 }
196 DecodedEncoderInstruction::InsertWithNameRefStatic { .. }
197 | DecodedEncoderInstruction::InsertWithNameRefDynamic { .. } => {
198 self.state = EncoderInstructionReaderState::ReadFirstInt {
199 reader: IntReader::new(b, ENCODER_INSERT_WITH_NAME_REF_STATIC.len()),
200 }
201 }
202 DecodedEncoderInstruction::InsertWithNameLiteral { .. } => {
203 self.state = EncoderInstructionReaderState::ReadFirstLiteral {
204 reader: LiteralReader::new_with_first_byte(
205 b,
206 ENCODER_INSERT_WITH_NAME_LITERAL.len(),
207 ),
208 }
209 }
210 DecodedEncoderInstruction::NoInstruction => {
211 unreachable!("We must have instruction at this point");
212 }
213 }
214 Ok(())
215 }
216
217 /// # Errors
218 ///
219 /// 1) `NeedMoreData` if the reader needs more data
220 /// 2) `ClosedCriticalStream`
221 /// 3) other errors will be translated to `EncoderStream` by the caller of this function.
222 pub fn read_instructions<T: ReadByte + Reader>(
223 &mut self,
224 recv: &mut T,
225 ) -> Res<DecodedEncoderInstruction> {
226 qdebug!("[{self}] reading instructions");
227 loop {
228 match &mut self.state {
229 EncoderInstructionReaderState::ReadInstruction => {
230 self.decode_instruction_type(recv)?;
231 }
232 EncoderInstructionReaderState::ReadFirstInt { reader } => {
233 let val = reader.read(recv)?;
234
235 qtrace!("[{self}] First varint read {val}");
236 match &mut self.instruction {
237 DecodedEncoderInstruction::Capacity { value: v, .. }
238 | DecodedEncoderInstruction::Duplicate { index: v } => {
239 *v = val;
240 self.state = EncoderInstructionReaderState::Done;
241 }
242 DecodedEncoderInstruction::InsertWithNameRefStatic { index, .. }
243 | DecodedEncoderInstruction::InsertWithNameRefDynamic { index, .. } => {
244 *index = val;
245 self.state = EncoderInstructionReaderState::ReadFirstLiteral {
246 reader: LiteralReader::default(),
247 };
248 }
249 _ => unreachable!("This instruction cannot be in this state"),
250 }
251 }
252 EncoderInstructionReaderState::ReadFirstLiteral { reader } => {
253 let val = reader.read(recv)?;
254
255 qtrace!("[{self}] first literal read {val:?}");
256 match &mut self.instruction {
257 DecodedEncoderInstruction::InsertWithNameRefStatic { value, .. }
258 | DecodedEncoderInstruction::InsertWithNameRefDynamic { value, .. } => {
259 *value = val;
260 self.state = EncoderInstructionReaderState::Done;
261 }
262 DecodedEncoderInstruction::InsertWithNameLiteral { name, .. } => {
263 *name = val;
264 self.state = EncoderInstructionReaderState::ReadSecondLiteral {
265 reader: LiteralReader::default(),
266 };
267 }
268 _ => unreachable!("This instruction cannot be in this state"),
269 }
270 }
271 EncoderInstructionReaderState::ReadSecondLiteral { reader } => {
272 let val = reader.read(recv)?;
273
274 qtrace!("[{self}] second literal read {val:?}");
275 match &mut self.instruction {
276 DecodedEncoderInstruction::InsertWithNameLiteral { value, .. } => {
277 *value = val;
278 self.state = EncoderInstructionReaderState::Done;
279 }
280 _ => unreachable!("This instruction cannot be in this state"),
281 }
282 }
283 EncoderInstructionReaderState::Done => {}
284 }
285 if matches!(self.state, EncoderInstructionReaderState::Done) {
286 self.state = EncoderInstructionReaderState::ReadInstruction;
287 break Ok(mem::replace(
288 &mut self.instruction,
289 DecodedEncoderInstruction::NoInstruction,
290 ));
291 }
292 }
293 }
294 }
295
296 #[cfg(test)]
297 mod test {
298
299 use super::{EncoderInstruction, EncoderInstructionReader, QpackData};
300 use crate::{reader::test_receiver::TestReceiver, Error};
301
302 fn test_encoding_decoding(instruction: &EncoderInstruction, use_huffman: bool) {
303 let mut buf = QpackData::default();
304 instruction.marshal(&mut buf, use_huffman);
305 let mut test_receiver: TestReceiver = TestReceiver::default();
306 test_receiver.write(&buf);
307 let mut reader = EncoderInstructionReader::new();
308 assert_eq!(
309 reader.read_instructions(&mut test_receiver).unwrap(),
310 instruction.into()
311 );
312 }
313
314 #[test]
315 fn encoding_decoding_instructions() {
316 test_encoding_decoding(&EncoderInstruction::Capacity { value: 1 }, false);
317 test_encoding_decoding(&EncoderInstruction::Capacity { value: 10_000 }, false);
318
319 test_encoding_decoding(
320 &EncoderInstruction::InsertWithNameRefStatic {
321 index: 1,
322 value: &[0x62, 0x64, 0x65],
323 },
324 false,
325 );
326 test_encoding_decoding(
327 &EncoderInstruction::InsertWithNameRefStatic {
328 index: 1,
329 value: &[0x62, 0x64, 0x65],
330 },
331 true,
332 );
333 test_encoding_decoding(
334 &EncoderInstruction::InsertWithNameRefStatic {
335 index: 10_000,
336 value: &[0x62, 0x64, 0x65],
337 },
338 false,
339 );
340 test_encoding_decoding(
341 &EncoderInstruction::InsertWithNameRefStatic {
342 index: 10_000,
343 value: &[0x62, 0x64, 0x65],
344 },
345 true,
346 );
347
348 test_encoding_decoding(
349 &EncoderInstruction::InsertWithNameRefDynamic {
350 index: 1,
351 value: &[0x62, 0x64, 0x65],
352 },
353 false,
354 );
355 test_encoding_decoding(
356 &EncoderInstruction::InsertWithNameRefDynamic {
357 index: 1,
358 value: &[0x62, 0x64, 0x65],
359 },
360 true,
361 );
362 test_encoding_decoding(
363 &EncoderInstruction::InsertWithNameRefDynamic {
364 index: 10_000,
365 value: &[0x62, 0x64, 0x65],
366 },
367 false,
368 );
369 test_encoding_decoding(
370 &EncoderInstruction::InsertWithNameRefDynamic {
371 index: 10_000,
372 value: &[0x62, 0x64, 0x65],
373 },
374 true,
375 );
376
377 test_encoding_decoding(
378 &EncoderInstruction::InsertWithNameLiteral {
379 name: &[0x62, 0x64, 0x65],
380 value: &[0x62, 0x64, 0x65],
381 },
382 false,
383 );
384 test_encoding_decoding(
385 &EncoderInstruction::InsertWithNameLiteral {
386 name: &[0x62, 0x64, 0x65],
387 value: &[0x62, 0x64, 0x65],
388 },
389 true,
390 );
391
392 test_encoding_decoding(&EncoderInstruction::Duplicate { index: 1 }, false);
393 test_encoding_decoding(&EncoderInstruction::Duplicate { index: 10_000 }, false);
394 }
395
396 fn test_encoding_decoding_slow_reader(instruction: &EncoderInstruction, use_huffman: bool) {
397 let mut buf = QpackData::default();
398 instruction.marshal(&mut buf, use_huffman);
399 let mut test_receiver: TestReceiver = TestReceiver::default();
400 let mut decoder = EncoderInstructionReader::new();
401 for i in 0..buf.len() - 1 {
402 test_receiver.write(&buf[i..=i]);
403 assert_eq!(
404 decoder.read_instructions(&mut test_receiver),
405 Err(Error::NeedMoreData)
406 );
407 }
408 test_receiver.write(&buf[buf.len() - 1..buf.len()]);
409 assert_eq!(
410 decoder.read_instructions(&mut test_receiver).unwrap(),
411 instruction.into()
412 );
413 }
414
415 #[test]
416 fn encoding_decoding_instructions_slow_reader() {
417 test_encoding_decoding_slow_reader(&EncoderInstruction::Capacity { value: 1 }, false);
418 test_encoding_decoding_slow_reader(&EncoderInstruction::Capacity { value: 10_000 }, false);
419
420 test_encoding_decoding_slow_reader(
421 &EncoderInstruction::InsertWithNameRefStatic {
422 index: 1,
423 value: &[0x62, 0x64, 0x65],
424 },
425 false,
426 );
427 test_encoding_decoding_slow_reader(
428 &EncoderInstruction::InsertWithNameRefStatic {
429 index: 1,
430 value: &[0x62, 0x64, 0x65],
431 },
432 true,
433 );
434 test_encoding_decoding_slow_reader(
435 &EncoderInstruction::InsertWithNameRefStatic {
436 index: 10_000,
437 value: &[0x62, 0x64, 0x65],
438 },
439 false,
440 );
441 test_encoding_decoding_slow_reader(
442 &EncoderInstruction::InsertWithNameRefStatic {
443 index: 10_000,
444 value: &[0x62, 0x64, 0x65],
445 },
446 true,
447 );
448
449 test_encoding_decoding_slow_reader(
450 &EncoderInstruction::InsertWithNameRefDynamic {
451 index: 1,
452 value: &[0x62, 0x64, 0x65],
453 },
454 false,
455 );
456 test_encoding_decoding_slow_reader(
457 &EncoderInstruction::InsertWithNameRefDynamic {
458 index: 1,
459 value: &[0x62, 0x64, 0x65],
460 },
461 true,
462 );
463 test_encoding_decoding_slow_reader(
464 &EncoderInstruction::InsertWithNameRefDynamic {
465 index: 10_000,
466 value: &[0x62, 0x64, 0x65],
467 },
468 false,
469 );
470 test_encoding_decoding_slow_reader(
471 &EncoderInstruction::InsertWithNameRefDynamic {
472 index: 10_000,
473 value: &[0x62, 0x64, 0x65],
474 },
475 true,
476 );
477
478 test_encoding_decoding_slow_reader(
479 &EncoderInstruction::InsertWithNameLiteral {
480 name: &[0x62, 0x64, 0x65],
481 value: &[0x62, 0x64, 0x65],
482 },
483 false,
484 );
485 test_encoding_decoding_slow_reader(
486 &EncoderInstruction::InsertWithNameLiteral {
487 name: &[0x62, 0x64, 0x65],
488 value: &[0x62, 0x64, 0x65],
489 },
490 true,
491 );
492
493 test_encoding_decoding_slow_reader(&EncoderInstruction::Duplicate { index: 1 }, false);
494 test_encoding_decoding_slow_reader(&EncoderInstruction::Duplicate { index: 10_000 }, false);
495 }
496
497 #[test]
498 fn decoding_error() {
499 let mut test_receiver: TestReceiver = TestReceiver::default();
500 // EncoderInstruction::Capacity with overflow
501 test_receiver.write(&[
502 0x3f, 0xc1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff, 0x02,
503 ]);
504 let mut decoder = EncoderInstructionReader::new();
505 assert_eq!(
506 decoder.read_instructions(&mut test_receiver),
507 Err(Error::IntegerOverflow)
508 );
509
510 let mut test_receiver: TestReceiver = TestReceiver::default();
511 // EncoderInstruction::InsertWithNameRefStatic with overflow of index value.
512 test_receiver.write(&[
513 0xff, 0xc1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff, 0x02, 0x00, 0x00,
514 ]);
515 let mut decoder = EncoderInstructionReader::new();
516 assert_eq!(
517 decoder.read_instructions(&mut test_receiver),
518 Err(Error::IntegerOverflow)
519 );
520
521 let mut test_receiver: TestReceiver = TestReceiver::default();
522 // EncoderInstruction::InsertWithNameRefStatic with a garbage value.
523 test_receiver.write(&[0xc1, 0x81, 0x00]);
524 let mut decoder = EncoderInstructionReader::new();
525 assert_eq!(
526 decoder.read_instructions(&mut test_receiver),
527 Err(Error::HuffmanDecompressionFailed)
528 );
529 }
530 }