• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #![rustfmt::skip]
15 
16 use crate::h3::parts::Parts;
17 use crate::h3::qpack::error::ErrorCode::DecoderStreamError;
18 use crate::h3::qpack::error::H3errorQpack;
19 use crate::h3::qpack::format::decoder::DecResult;
20 use crate::h3::qpack::integer::{Integer, IntegerDecoder, IntegerEncoder};
21 use crate::h3::qpack::table::{DynamicTable, Field, TableIndex, TableSearcher};
22 use crate::h3::qpack::{DecoderInstPrefixBit, DecoderInstruction, EncoderInstruction, PrefixMask};
23 use crate::headers::HeadersIntoIter;
24 use crate::h3::pseudo::PseudoHeaders;
25 use std::arch::asm;
26 use std::cmp::{max, Ordering};
27 use std::collections::{HashMap, VecDeque};
28 use std::result;
29 use std::sync::Arc;
30 
31 pub struct ReprEncoder<'a> {
32     table: &'a mut DynamicTable,
33     draining_index: usize,
34     allow_post: bool,
35     insert_length: &'a mut usize,
36 }
37 
38 impl<'a> ReprEncoder<'a> {
39     /// Creates a new, empty `ReprEncoder`.
40     /// # Examples
41 //     ```no_run
42 //     use ylong_http::h3::qpack::table::DynamicTable;
43 //     use ylong_http::h3::qpack::format::encoder::ReprEncoder;
44 //     let mut table = DynamicTable::new(4096);
45 //     let mut insert_length = 0;
46 //     let mut encoder = ReprEncoder::new(&mut table, 0, true, &mut insert_length);
47 //     ```
new( table: &'a mut DynamicTable, draining_index: usize, allow_post: bool, insert_length: &'a mut usize, ) -> Self48     pub fn new(
49         table: &'a mut DynamicTable,
50         draining_index: usize,
51         allow_post: bool,
52         insert_length: &'a mut usize,
53     ) -> Self {
54         Self {
55             table,
56             draining_index,
57             allow_post,
58             insert_length,
59         }
60     }
61 
62     /// written to `buffer` and the length of the decoded content will be returned.
63     /// # Examples
64 //     ```no_run
65 //     use std::collections::VecDeque;use ylong_http::h3::qpack::table::DynamicTable;
66 //     use ylong_http::h3::qpack::format::encoder::ReprEncoder;
67 //     let mut table = DynamicTable::new(4096);
68 //     let mut insert_length = 0;
69 //     let mut encoder = ReprEncoder::new(&mut table, 0, true, &mut insert_length);
70 //     let mut qpack_buffer = [0u8; 1024];
71 //     let mut stream_buffer = [0u8; 1024]; // stream buffer
72 //     let mut insert_list = VecDeque::new(); // fileds to insert
73 //     let mut required_insert_count = 0; // RFC required.
74 //     let mut field_iter = None; // for field iterator
75 //     let mut field_state = None; // for field encode state
76 //     encoder.encode(&mut field_iter, &mut field_state, &mut qpack_buffer, &mut stream_buffer, &mut insert_list, &mut required_insert_count);
encode( &mut self, field_iter: &mut Option<PartsIter>, field_state: &mut Option<ReprEncodeState>, encoder_buffer: &mut [u8], stream_buffer: &mut [u8], insert_list: &mut VecDeque<(Field, String)>, required_insert_count: &mut usize, ) -> (usize, usize)77     pub(crate) fn encode(
78         &mut self,
79         field_iter: &mut Option<PartsIter>,
80         field_state: &mut Option<ReprEncodeState>,
81         encoder_buffer: &mut [u8],
82         stream_buffer: &mut [u8],
83         insert_list: &mut VecDeque<(Field, String)>,
84         required_insert_count: &mut usize,
85     ) -> (usize, usize) {
86         let mut cur_encoder = 0;
87         let mut cur_stream = 0;
88         let mut base = self.table.insert_count;
89         if let Some(mut iter) = field_iter.take() {
90             while let Some((h, v)) = iter.next() {
91                 let searcher = TableSearcher::new(self.table);
92                 let mut stream_result: Result<usize, ReprEncodeState> = Result::Ok(0);
93                 let mut encoder_result: Result<usize, ReprEncodeState> = Result::Ok(0);
94                 let static_index = searcher.find_index_static(&h, &v);
95                 if static_index != Some(TableIndex::None) {
96                     if let Some(TableIndex::Field(index)) = static_index {
97                         // Encode as index in static table
98                         stream_result =
99                             Indexed::new(index, true).encode(&mut stream_buffer[cur_stream..]);
100                     }
101                 } else {
102                     let mut dynamic_index = searcher.find_index_dynamic(&h, &v);
103                     let static_name_index = searcher.find_index_name_static(&h, &v);
104                     let mut dynamic_name_index = Some(TableIndex::None);
105                     if dynamic_index == Some(TableIndex::None) || !self.should_index(&dynamic_index)
106                     {
107                         // if index is close to eviction, drop it and use duplicate
108                         // let dyn_index = dynamic_index.clone();
109                         // dynamic_index = Some(TableIndex::None);
110                         let mut is_duplicate = false;
111                         if static_name_index == Some(TableIndex::None) {
112                             dynamic_name_index = searcher.find_index_name_dynamic(&h, &v);
113                         }
114 
115                         if self.table.have_enough_space(&h, &v, self.insert_length) {
116                             if !self.should_index(&dynamic_index) {
117                                 if let Some(TableIndex::Field(index)) = dynamic_index {
118                                     encoder_result = Duplicate::new(base - index - 1)
119                                         .encode(&mut encoder_buffer[cur_encoder..]);
120                                     self.table.update(h.clone(), v.clone());
121                                     base = max(base, self.table.insert_count);
122                                     dynamic_index =
123                                         Some(TableIndex::Field(self.table.insert_count - 1));
124                                     is_duplicate = true;
125                                 }
126                             } else {
127                                 encoder_result = match (
128                                     &static_name_index,
129                                     &dynamic_name_index,
130                                     self.should_index(&dynamic_name_index),
131                                 ) {
132                                     // insert with name reference in static table
133                                     (Some(TableIndex::FieldName(index)), _, _) => {
134                                         InsertWithName::new(
135                                             *index,
136                                             v.clone().into_bytes(),
137                                             false,
138                                             true,
139                                         )
140                                         .encode(&mut encoder_buffer[cur_encoder..])
141                                     }
142                                     // insert with name reference in dynamic table
143                                     (_, Some(TableIndex::FieldName(index)), true) => {
144                                         // convert abs index to rel index
145                                         InsertWithName::new(
146                                             base - index - 1,
147                                             v.clone().into_bytes(),
148                                             false,
149                                             false,
150                                         )
151                                         .encode(&mut encoder_buffer[cur_encoder..])
152                                     }
153                                     // Duplicate
154                                     (_, Some(TableIndex::FieldName(index)), false) => {
155                                         let res = Duplicate::new(*index)
156                                             .encode(&mut encoder_buffer[cur_encoder..]);
157                                         self.table.update(h.clone(), v.clone());
158                                         base = max(base, self.table.insert_count);
159                                         dynamic_name_index = Some(TableIndex::FieldName(
160                                             self.table.insert_count - 1,
161                                         ));
162                                         is_duplicate = true;
163                                         res
164                                     }
165                                     // insert with literal name
166                                     (_, _, _) => InsertWithLiteral::new(
167                                         h.clone().into_string().into_bytes(),
168                                         v.clone().into_bytes(),
169                                         false,
170                                     )
171                                     .encode(&mut encoder_buffer[cur_encoder..]),
172                                 }
173                             };
174                             if self.table.size() + h.len() + v.len() + 32 >= self.table.capacity() {
175                                 self.draining_index += 1;
176                             }
177                             insert_list.push_back((h.clone(), v.clone()));
178                             *self.insert_length += h.len() + v.len() + 32;
179                         }
180                         if self.allow_post && !is_duplicate {
181                             for (post_index, (t_h, t_v)) in insert_list.iter().enumerate() {
182                                 if t_h == &h && t_v == &v {
183                                     dynamic_index = Some(TableIndex::Field(post_index))
184                                 }
185                                 if t_h == &h {
186                                     dynamic_name_index = Some(TableIndex::FieldName(post_index));
187                                 }
188                             }
189                         }
190                     }
191 
192                     if dynamic_index == Some(TableIndex::None) {
193                         if dynamic_name_index != Some(TableIndex::None) {
194                             //Encode with name reference in dynamic table
195                             if let Some(TableIndex::FieldName(index)) = dynamic_name_index {
196                                 // use post-base index
197                                 if base <= index {
198                                     stream_result = IndexingWithPostName::new(
199                                         index - base,
200                                         v.clone().into_bytes(),
201                                         false,
202                                         false,
203                                     )
204                                     .encode(&mut stream_buffer[cur_stream..]);
205                                 } else {
206                                     stream_result = IndexingWithName::new(
207                                         base - index - 1,
208                                         v.clone().into_bytes(),
209                                         false,
210                                         false,
211                                         false,
212                                     )
213                                     .encode(&mut stream_buffer[cur_stream..]);
214                                 }
215                                 *required_insert_count = max(*required_insert_count, index + 1);
216                             }
217                         } else {
218                             // Encode with name reference in static table
219                             // or Encode as Literal
220                             if static_name_index != Some(TableIndex::None) {
221                                 if let Some(TableIndex::FieldName(index)) = static_name_index {
222                                     stream_result = IndexingWithName::new(
223                                         index,
224                                         v.into_bytes(),
225                                         false,
226                                         true,
227                                         false,
228                                     )
229                                     .encode(&mut stream_buffer[cur_stream..]);
230                                 }
231                             } else {
232                                 stream_result = IndexingWithLiteral::new(
233                                     h.into_string().into_bytes(),
234                                     v.into_bytes(),
235                                     false,
236                                     false,
237                                 )
238                                 .encode(&mut stream_buffer[cur_stream..]);
239                             }
240                         }
241                     } else {
242                         assert!(dynamic_index != Some(TableIndex::None));
243                         // Encode with index in dynamic table
244                         if let Some(TableIndex::Field(index)) = dynamic_index {
245                             // use post-base index
246                             if base <= index {
247                                 stream_result = IndexedWithPostName::new(index - base)
248                                     .encode(&mut stream_buffer[cur_stream..]);
249                             } else {
250                                 stream_result = Indexed::new(base - index - 1, false)
251                                     .encode(&mut stream_buffer[cur_stream..]);
252                             }
253                             *required_insert_count = max(*required_insert_count, index + 1);
254                         }
255                     }
256                 }
257 
258                 match (encoder_result, stream_result) {
259                     (Ok(encoder_size), Ok(stream_size)) => {
260                         cur_stream += stream_size;
261                         cur_encoder += encoder_size;
262                     }
263                     (Err(state), Ok(_)) => {
264                         *field_iter = Some(iter);
265                         *field_state = Some(state);
266                         return (encoder_buffer.len(), stream_buffer.len());
267                     }
268                     (Ok(_), Err(state)) => {
269                         *field_iter = Some(iter);
270                         *field_state = Some(state);
271                         return (encoder_buffer.len(), stream_buffer.len());
272                     }
273                     (Err(_), Err(state)) => {
274                         *field_iter = Some(iter);
275                         *field_state = Some(state);
276                         return (encoder_buffer.len(), stream_buffer.len());
277                     }
278                 }
279             }
280         }
281 
282         (cur_encoder, cur_stream)
283     }
284     // ## 2.1.1.1. Avoiding Prohibited Insertions
285     // To ensure that the encoder is not prevented from adding new entries, the encoder can
286     // avoid referencing entries that are close to eviction. Rather than reference such an
287     // entry, the encoder can emit a Duplicate instruction (Section 4.3.4) and reference
288     // the duplicate instead.
289     //
290     // Determining which entries are too close to eviction to reference is an encoder preference.
291     // One heuristic is to target a fixed amount of available space in the dynamic table:
292     // either unused space or space that can be reclaimed by evicting non-blocking entries.
293     // To achieve this, the encoder can maintain a draining index, which is the smallest
294     // absolute index (Section 3.2.4) in the dynamic table that it will emit a reference for.
295     // As new entries are inserted, the encoder increases the draining index to maintain the
296     // section of the table that it will not reference. If the encoder does not create new
297     // references to entries with an absolute index lower than the draining index, the number
298     // of unacknowledged references to those entries will eventually become zero, allowing
299     // them to be evicted.
300     //
301     //     <-- Newer Entries          Older Entries -->
302     // (Larger Indices)       (Smaller Indices)
303     // +--------+---------------------------------+----------+
304     // | Unused |          Referenceable          | Draining |
305     // | Space  |             Entries             | Entries  |
306     // +--------+---------------------------------+----------+
307     // ^                                 ^          ^
308     // |                                 |          |
309     // Insertion Point                 Draining Index  Dropping
310     // Point
should_index(&self, index: &Option<TableIndex>) -> bool311     pub(crate) fn should_index(&self, index: &Option<TableIndex>) -> bool {
312         match index {
313             Some(TableIndex::Field(x)) => {
314                 if *x < self.draining_index {
315                     return false;
316                 }
317                 true
318             }
319             Some(TableIndex::FieldName(x)) => {
320                 if *x < self.draining_index {
321                     return false;
322                 }
323                 true
324             }
325             _ => true,
326         }
327     }
328 }
329 
330 pub(crate) enum ReprEncodeState {
331     SetCap(SetCap),
332     Indexed(Indexed),
333     InsertWithName(InsertWithName),
334     InsertWithLiteral(InsertWithLiteral),
335     IndexingWithName(IndexingWithName),
336     IndexingWithPostName(IndexingWithPostName),
337     IndexingWithLiteral(IndexingWithLiteral),
338     IndexedWithPostName(IndexedWithPostName),
339     Duplicate(Duplicate),
340 }
341 
342 pub(crate) struct SetCap {
343     capacity: Integer,
344 }
345 
346 impl SetCap {
from(capacity: Integer) -> Self347     fn from(capacity: Integer) -> Self {
348         Self { capacity }
349     }
350 
new(capacity: usize) -> Self351     pub(crate) fn new(capacity: usize) -> Self {
352         Self {
353             capacity: Integer::index(0x20, capacity, PrefixMask::SETCAP.0),
354         }
355     }
356 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>357     pub(crate) fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
358         self.capacity
359             .encode(dst)
360             .map_err(|e| ReprEncodeState::SetCap(SetCap::from(e)))
361     }
362 }
363 
364 pub(crate) struct Duplicate {
365     index: Integer,
366 }
367 
368 impl Duplicate {
from(index: Integer) -> Self369     fn from(index: Integer) -> Self {
370         Self { index }
371     }
372 
new(index: usize) -> Self373     fn new(index: usize) -> Self {
374         Self {
375             index: Integer::index(0x00, index, PrefixMask::DUPLICATE.0),
376         }
377     }
378 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>379     fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
380         self.index
381             .encode(dst)
382             .map_err(|e| ReprEncodeState::Duplicate(Duplicate::from(e)))
383     }
384 }
385 
386 pub(crate) struct Indexed {
387     index: Integer,
388 }
389 
390 impl Indexed {
from(index: Integer) -> Self391     fn from(index: Integer) -> Self {
392         Self { index }
393     }
394 
new(index: usize, is_static: bool) -> Self395     fn new(index: usize, is_static: bool) -> Self {
396         if is_static {
397             // in static table
398             Self {
399                 index: Integer::index(0xc0, index, PrefixMask::INDEXED.0),
400             }
401         } else {
402             // in dynamic table
403             Self {
404                 index: Integer::index(0x80, index, PrefixMask::INDEXED.0),
405             }
406         }
407     }
408 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>409     fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
410         self.index
411             .encode(dst)
412             .map_err(|e| ReprEncodeState::Indexed(Indexed::from(e)))
413     }
414 }
415 
416 pub(crate) struct IndexedWithPostName {
417     index: Integer,
418 }
419 
420 impl IndexedWithPostName {
from(index: Integer) -> Self421     fn from(index: Integer) -> Self {
422         Self { index }
423     }
424 
new(index: usize) -> Self425     fn new(index: usize) -> Self {
426         Self {
427             index: Integer::index(0x10, index, PrefixMask::INDEXINGWITHPOSTNAME.0),
428         }
429     }
430 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>431     fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
432         self.index
433             .encode(dst)
434             .map_err(|e| ReprEncodeState::IndexedWithPostName(IndexedWithPostName::from(e)))
435     }
436 }
437 
438 pub(crate) struct InsertWithName {
439     inner: IndexAndValue,
440 }
441 
442 impl InsertWithName {
from(inner: IndexAndValue) -> Self443     fn from(inner: IndexAndValue) -> Self {
444         Self { inner }
445     }
446 
new(index: usize, value: Vec<u8>, is_huffman: bool, is_static: bool) -> Self447     fn new(index: usize, value: Vec<u8>, is_huffman: bool, is_static: bool) -> Self {
448         if is_static {
449             Self {
450                 inner: IndexAndValue::new()
451                     .set_index(0xc0, index, PrefixMask::INSERTWITHINDEX.0)
452                     .set_value(value, is_huffman),
453             }
454         } else {
455             Self {
456                 inner: IndexAndValue::new()
457                     .set_index(0x80, index, PrefixMask::INSERTWITHINDEX.0)
458                     .set_value(value, is_huffman),
459             }
460         }
461     }
462 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>463     fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
464         self.inner
465             .encode(dst)
466             .map_err(|e| ReprEncodeState::InsertWithName(InsertWithName::from(e)))
467     }
468 }
469 
470 pub(crate) struct IndexingWithName {
471     inner: IndexAndValue,
472 }
473 
474 impl IndexingWithName {
from(inner: IndexAndValue) -> Self475     fn from(inner: IndexAndValue) -> Self {
476         Self { inner }
477     }
478 
new( index: usize, value: Vec<u8>, is_huffman: bool, is_static: bool, no_permit: bool, ) -> Self479     fn new(
480         index: usize,
481         value: Vec<u8>,
482         is_huffman: bool,
483         is_static: bool,
484         no_permit: bool,
485     ) -> Self {
486         match (no_permit, is_static) {
487             (true, true) => Self {
488                 inner: IndexAndValue::new()
489                     .set_index(0x70, index, PrefixMask::INDEXINGWITHNAME.0)
490                     .set_value(value, is_huffman),
491             },
492             (true, false) => Self {
493                 inner: IndexAndValue::new()
494                     .set_index(0x60, index, PrefixMask::INDEXINGWITHNAME.0)
495                     .set_value(value, is_huffman),
496             },
497             (false, true) => Self {
498                 inner: IndexAndValue::new()
499                     .set_index(0x50, index, PrefixMask::INDEXINGWITHNAME.0)
500                     .set_value(value, is_huffman),
501             },
502             (false, false) => Self {
503                 inner: IndexAndValue::new()
504                     .set_index(0x40, index, PrefixMask::INDEXINGWITHNAME.0)
505                     .set_value(value, is_huffman),
506             },
507         }
508     }
509 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>510     fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
511         self.inner
512             .encode(dst)
513             .map_err(|e| ReprEncodeState::IndexingWithName(IndexingWithName::from(e)))
514     }
515 }
516 
517 pub(crate) struct IndexingWithPostName {
518     inner: IndexAndValue,
519 }
520 
521 impl IndexingWithPostName {
from(inner: IndexAndValue) -> Self522     fn from(inner: IndexAndValue) -> Self {
523         Self { inner }
524     }
525 
new(index: usize, value: Vec<u8>, is_huffman: bool, no_permit: bool) -> Self526     fn new(index: usize, value: Vec<u8>, is_huffman: bool, no_permit: bool) -> Self {
527         if no_permit {
528             Self {
529                 inner: IndexAndValue::new()
530                     .set_index(0x08, index, PrefixMask::INDEXINGWITHPOSTNAME.0)
531                     .set_value(value, is_huffman),
532             }
533         } else {
534             Self {
535                 inner: IndexAndValue::new()
536                     .set_index(0x00, index, PrefixMask::INDEXINGWITHPOSTNAME.0)
537                     .set_value(value, is_huffman),
538             }
539         }
540     }
541 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>542     fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
543         self.inner
544             .encode(dst)
545             .map_err(|e| ReprEncodeState::IndexingWithPostName(IndexingWithPostName::from(e)))
546     }
547 }
548 
549 pub(crate) struct IndexingWithLiteral {
550     inner: NameAndValue,
551 }
552 
553 impl IndexingWithLiteral {
new(name: Vec<u8>, value: Vec<u8>, is_huffman: bool, no_permit: bool) -> Self554     fn new(name: Vec<u8>, value: Vec<u8>, is_huffman: bool, no_permit: bool) -> Self {
555         match (no_permit, is_huffman) {
556             (true, true) => Self {
557                 inner: NameAndValue::new()
558                     .set_index(0x38, name.len(), PrefixMask::INDEXINGWITHLITERAL.0)
559                     .set_name_and_value(name, value, is_huffman),
560             },
561             (true, false) => Self {
562                 inner: NameAndValue::new()
563                     .set_index(0x30, name.len(), PrefixMask::INDEXINGWITHLITERAL.0)
564                     .set_name_and_value(name, value, is_huffman),
565             },
566             (false, true) => Self {
567                 inner: NameAndValue::new()
568                     .set_index(0x28, name.len(), PrefixMask::INDEXINGWITHLITERAL.0)
569                     .set_name_and_value(name, value, is_huffman),
570             },
571             (false, false) => Self {
572                 inner: NameAndValue::new()
573                     .set_index(0x20, name.len(), PrefixMask::INDEXINGWITHLITERAL.0)
574                     .set_name_and_value(name, value, is_huffman),
575             },
576         }
577     }
578 
from(inner: NameAndValue) -> Self579     fn from(inner: NameAndValue) -> Self {
580         Self { inner }
581     }
582 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>583     fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
584         self.inner
585             .encode(dst)
586             .map_err(|e| ReprEncodeState::InsertWithLiteral(InsertWithLiteral::from(e)))
587     }
588 }
589 
590 pub(crate) struct InsertWithLiteral {
591     inner: NameAndValue,
592 }
593 
594 impl InsertWithLiteral {
new(name: Vec<u8>, value: Vec<u8>, is_huffman: bool) -> Self595     fn new(name: Vec<u8>, value: Vec<u8>, is_huffman: bool) -> Self {
596         if is_huffman {
597             Self {
598                 inner: NameAndValue::new()
599                     .set_index(0x60, name.len(), PrefixMask::INSERTWITHLITERAL.0)
600                     .set_name_and_value(name, value, is_huffman),
601             }
602         } else {
603             Self {
604                 inner: NameAndValue::new()
605                     .set_index(0x40, name.len(), PrefixMask::INSERTWITHLITERAL.0)
606                     .set_name_and_value(name, value, is_huffman),
607             }
608         }
609     }
610 
from(inner: NameAndValue) -> Self611     fn from(inner: NameAndValue) -> Self {
612         Self { inner }
613     }
614 
encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState>615     fn encode(self, dst: &mut [u8]) -> Result<usize, ReprEncodeState> {
616         self.inner
617             .encode(dst)
618             .map_err(|e| ReprEncodeState::InsertWithLiteral(InsertWithLiteral::from(e)))
619     }
620 }
621 
622 pub(crate) struct IndexAndValue {
623     index: Option<Integer>,
624     value_length: Option<Integer>,
625     value_octets: Option<Octets>,
626 }
627 macro_rules! check_and_encode {
628     ($item: expr, $dst: expr, $cur: expr, $self: expr) => {{
629         if let Some(i) = $item.take() {
630             match i.encode($dst) {
631                 Ok(len) => $cur += len,
632                 Err(e) => {
633                     $item = Some(e);
634                     return Err($self);
635                 }
636             };
637         }
638     }};
639 }
640 impl IndexAndValue {
new() -> Self641     fn new() -> Self {
642         Self {
643             index: None,
644             value_length: None,
645             value_octets: None,
646         }
647     }
648 
set_index(mut self, pre: u8, index: usize, mask: u8) -> Self649     fn set_index(mut self, pre: u8, index: usize, mask: u8) -> Self {
650         self.index = Some(Integer::index(pre, index, mask));
651         self
652     }
653 
set_value(mut self, value: Vec<u8>, is_huffman: bool) -> Self654     fn set_value(mut self, value: Vec<u8>, is_huffman: bool) -> Self {
655         self.value_length = Some(Integer::length(value.len(), is_huffman));
656         self.value_octets = Some(Octets::new(value));
657         self
658     }
659 
encode(mut self, dst: &mut [u8]) -> Result<usize, Self>660     fn encode(mut self, dst: &mut [u8]) -> Result<usize, Self> {
661         let mut cur = 0;
662         check_and_encode!(self.index, &mut dst[cur..], cur, self);
663         check_and_encode!(self.value_length, &mut dst[cur..], cur, self);
664         check_and_encode!(self.value_octets, &mut dst[cur..], cur, self);
665         Ok(cur)
666     }
667 }
668 
669 pub(crate) struct NameAndValue {
670     index: Option<Integer>,
671     name_length: Option<Integer>,
672     name_octets: Option<Octets>,
673     value_length: Option<Integer>,
674     value_octets: Option<Octets>,
675 }
676 
677 impl NameAndValue {
new() -> Self678     fn new() -> Self {
679         Self {
680             index: None,
681             name_length: None,
682             name_octets: None,
683             value_length: None,
684             value_octets: None,
685         }
686     }
687 
set_index(mut self, pre: u8, index: usize, mask: u8) -> Self688     fn set_index(mut self, pre: u8, index: usize, mask: u8) -> Self {
689         self.index = Some(Integer::index(pre, index, mask));
690         self
691     }
692 
set_name_and_value(mut self, name: Vec<u8>, value: Vec<u8>, is_huffman: bool) -> Self693     fn set_name_and_value(mut self, name: Vec<u8>, value: Vec<u8>, is_huffman: bool) -> Self {
694         self.name_length = Some(Integer::length(name.len(), is_huffman));
695         self.name_octets = Some(Octets::new(name));
696         self.value_length = Some(Integer::length(value.len(), is_huffman));
697         self.value_octets = Some(Octets::new(value));
698         self
699     }
700 
encode(mut self, dst: &mut [u8]) -> Result<usize, Self>701     fn encode(mut self, dst: &mut [u8]) -> Result<usize, Self> {
702         let mut cur = 0;
703         check_and_encode!(self.index, &mut dst[cur..], cur, self);
704         // check_and_encode!(self.name_length, &mut dst[cur..], cur, self); //no need for qpack cause it in index.
705         check_and_encode!(self.name_octets, &mut dst[cur..], cur, self);
706         check_and_encode!(self.value_length, &mut dst[cur..], cur, self);
707         check_and_encode!(self.value_octets, &mut dst[cur..], cur, self);
708         Ok(cur)
709     }
710 }
711 
712 macro_rules! state_def {
713     ($name: ident, $decoded: ty, $($state: ident),* $(,)?) => {
714         pub(crate) enum $name {
715             $(
716                 $state($state),
717             )*
718         }
719 
720         impl $name {
721             fn decode(self, buf: &mut &[u8]) -> DecResult<$decoded, $name> {
722                 match self {
723                     $(
724                         Self::$state(state) => state.decode(buf),
725                     )*
726                 }
727             }
728         }
729 
730         $(
731             impl From<$state> for $name {
732                 fn from(s: $state) -> Self {
733                     Self::$state(s)
734                 }
735             }
736         )*
737     }
738 }
739 
740 state_def!(InstDecodeState, DecoderInstruction, DecInstIndex);
741 pub(crate) struct DecInstDecoder<'a> {
742     buf: &'a [u8],
743 }
744 
745 impl<'a> DecInstDecoder<'a> {
new(buf: &'a [u8]) -> Self746     pub(crate) fn new(buf: &'a [u8]) -> Self {
747         Self { buf }
748     }
749 
decode( &mut self, ins_state: &mut Option<InstDecodeState>, ) -> Result<Option<DecoderInstruction>, H3errorQpack>750     pub(crate) fn decode(
751         &mut self,
752         ins_state: &mut Option<InstDecodeState>,
753     ) -> Result<Option<DecoderInstruction>, H3errorQpack> {
754         if self.buf.is_empty() {
755             return Ok(None);
756         }
757 
758         match ins_state
759             .take()
760             .unwrap_or_else(|| InstDecodeState::DecInstIndex(DecInstIndex::new()))
761             .decode(&mut self.buf)
762         {
763             // If `buf` is not enough to continue decoding a complete
764             // `Representation`, `Ok(None)` will be returned. Users need to call
765             // `save` to save the current state to a `ReprDecStateHolder`.
766             DecResult::NeedMore(state) => {
767                 *ins_state = Some(state);
768                 Ok(None)
769             }
770             DecResult::Decoded(repr) => Ok(Some(repr)),
771 
772             DecResult::Error(error) => Err(error),
773         }
774     }
775 }
776 state_def!(
777     DecInstIndexInner,
778     (DecoderInstPrefixBit, usize),
779     InstFirstByte,
780     InstTrailingBytes
781 );
782 
783 pub(crate) struct DecInstIndex {
784     inner: DecInstIndexInner,
785 }
786 
787 impl DecInstIndex {
new() -> Self788     fn new() -> Self {
789         Self::from_inner(InstFirstByte.into())
790     }
from_inner(inner: DecInstIndexInner) -> Self791     fn from_inner(inner: DecInstIndexInner) -> Self {
792         Self { inner }
793     }
decode(self, buf: &mut &[u8]) -> DecResult<DecoderInstruction, InstDecodeState>794     fn decode(self, buf: &mut &[u8]) -> DecResult<DecoderInstruction, InstDecodeState> {
795         match self.inner.decode(buf) {
796             DecResult::Decoded((DecoderInstPrefixBit::ACK, index)) => {
797                 DecResult::Decoded(DecoderInstruction::Ack { stream_id: index })
798             }
799             DecResult::Decoded((DecoderInstPrefixBit::STREAMCANCEL, index)) => {
800                 DecResult::Decoded(DecoderInstruction::StreamCancel { stream_id: index })
801             }
802             DecResult::Decoded((DecoderInstPrefixBit::INSERTCOUNTINCREMENT, index)) => {
803                 DecResult::Decoded(DecoderInstruction::InsertCountIncrement { increment: index })
804             }
805             DecResult::Error(e) => e.into(),
806             _ => DecResult::Error(H3errorQpack::ConnectionError(DecoderStreamError)),
807         }
808     }
809 }
810 
811 pub(crate) struct InstFirstByte;
812 
813 impl InstFirstByte {
decode( self, buf: &mut &[u8], ) -> DecResult<(DecoderInstPrefixBit, usize), DecInstIndexInner>814     fn decode(
815         self,
816         buf: &mut &[u8],
817     ) -> DecResult<(DecoderInstPrefixBit, usize), DecInstIndexInner> {
818         // If `buf` has been completely decoded here, return the current state.
819         if buf.is_empty() {
820             return DecResult::NeedMore(self.into());
821         }
822         let byte = buf[0];
823         let inst = DecoderInstPrefixBit::from_u8(byte);
824         let mask = inst.prefix_index_mask();
825 
826         // Moves the pointer of `buf` backward.
827         *buf = &buf[1..];
828         match IntegerDecoder::first_byte(byte, mask.0) {
829             // Return the ReprPrefixBit and index part value.
830             Ok(idx) => DecResult::Decoded((inst, idx)),
831             // Index part value is longer than index(i.e. use all 1 to represent), so it needs more bytes to decode.
832             Err(int) => InstTrailingBytes::new(inst, int).decode(buf),
833         }
834     }
835 }
836 
837 pub(crate) struct InstTrailingBytes {
838     inst: DecoderInstPrefixBit,
839     index: IntegerDecoder,
840 }
841 
842 impl InstTrailingBytes {
new(inst: DecoderInstPrefixBit, index: IntegerDecoder) -> Self843     fn new(inst: DecoderInstPrefixBit, index: IntegerDecoder) -> Self {
844         Self { inst, index }
845     }
decode( mut self, buf: &mut &[u8], ) -> DecResult<(DecoderInstPrefixBit, usize), DecInstIndexInner>846     fn decode(
847         mut self,
848         buf: &mut &[u8],
849     ) -> DecResult<(DecoderInstPrefixBit, usize), DecInstIndexInner> {
850         loop {
851             // If `buf` has been completely decoded here, return the current state.
852             if buf.is_empty() {
853                 return DecResult::NeedMore(self.into());
854             }
855 
856             let byte = buf[0];
857             *buf = &buf[1..];
858             // Updates trailing bytes until we get the index.
859             match self.index.next_byte(byte) {
860                 Ok(None) => {}
861                 Ok(Some(index)) => return DecResult::Decoded((self.inst, index)),
862                 Err(e) => return e.into(),
863             }
864         }
865     }
866 }
867 
868 pub(crate) struct Octets {
869     src: Vec<u8>,
870     idx: usize,
871 }
872 
873 impl Octets {
new(src: Vec<u8>) -> Self874     fn new(src: Vec<u8>) -> Self {
875         Self { src, idx: 0 }
876     }
877 
encode(mut self, dst: &mut [u8]) -> Result<usize, Self>878     fn encode(mut self, dst: &mut [u8]) -> Result<usize, Self> {
879         let mut cur = 0;
880 
881         let input_len = self.src.len() - self.idx;
882         let output_len = dst.len();
883 
884         if input_len == 0 {
885             return Ok(cur);
886         }
887 
888         match output_len.cmp(&input_len) {
889             Ordering::Greater | Ordering::Equal => {
890                 dst[..input_len].copy_from_slice(&self.src[self.idx..]);
891                 cur += input_len;
892                 Ok(cur)
893             }
894             Ordering::Less => {
895                 dst[..].copy_from_slice(&self.src[self.idx..self.idx + output_len]);
896                 self.idx += output_len;
897                 Err(self)
898             }
899         }
900     }
901 }
902 
903 pub(crate) struct PartsIter {
904     pseudo: PseudoHeaders,
905     map: HeadersIntoIter,
906     next_type: PartsIterDirection,
907 }
908 
909 /// `PartsIterDirection` is the `PartsIter`'s direction to get the next header.
910 enum PartsIterDirection {
911     Authority,
912     Method,
913     Path,
914     Scheme,
915     Status,
916     Other,
917 }
918 
919 impl PartsIter {
920     /// Creates a new `PartsIter` from the given `Parts`.
new(parts: Parts) -> Self921     pub(crate) fn new(parts: Parts) -> Self {
922         Self {
923             pseudo: parts.pseudo,
924             map: parts.map.into_iter(),
925             next_type: PartsIterDirection::Method,
926         }
927     }
928 
929     /// Gets headers in the order of `Method`, `Status`, `Scheme`, `Path`,
930     /// `Authority` and `Other`.
next(&mut self) -> Option<(Field, String)>931     fn next(&mut self) -> Option<(Field, String)> {
932         loop {
933             match self.next_type {
934                 PartsIterDirection::Method => match self.pseudo.take_method() {
935                     Some(value) => return Some((Field::Method, value)),
936                     None => self.next_type = PartsIterDirection::Status,
937                 },
938                 PartsIterDirection::Status => match self.pseudo.take_status() {
939                     Some(value) => return Some((Field::Status, value)),
940                     None => self.next_type = PartsIterDirection::Scheme,
941                 },
942                 PartsIterDirection::Scheme => match self.pseudo.take_scheme() {
943                     Some(value) => return Some((Field::Scheme, value)),
944                     None => self.next_type = PartsIterDirection::Path,
945                 },
946                 PartsIterDirection::Path => match self.pseudo.take_path() {
947                     Some(value) => return Some((Field::Path, value)),
948                     None => self.next_type = PartsIterDirection::Authority,
949                 },
950                 PartsIterDirection::Authority => match self.pseudo.take_authority() {
951                     Some(value) => return Some((Field::Authority, value)),
952                     None => self.next_type = PartsIterDirection::Other,
953                 },
954                 PartsIterDirection::Other => {
955                     return self
956                         .map
957                         .next()
958                         .map(|(h, v)| (Field::Other(h.to_string()), v.to_string().unwrap()));
959                 }
960             }
961         }
962     }
963 }
964