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 use std::arch::asm; 15 use std::cmp::{max, Ordering}; 16 use std::collections::{HashMap, HashSet, VecDeque}; 17 use std::sync::Arc; 18 use std::{mem, result}; 19 20 use crate::h3::parts::Parts; 21 use crate::h3::qpack::encoder::{EncodeMessage, UnackFields}; 22 use crate::h3::qpack::error::ErrorCode::DecoderStreamError; 23 use crate::h3::qpack::error::QpackError; 24 use crate::h3::qpack::format::decoder::{DecResult, LiteralString}; 25 use crate::h3::qpack::integer::{Integer, IntegerDecoder, IntegerEncoder}; 26 use crate::h3::qpack::table::{DynamicTable, NameField, SearchResult, TableIndex, TableSearcher}; 27 use crate::h3::qpack::{DecoderInstPrefixBit, DecoderInstruction, EncoderInstruction, PrefixMask}; 28 use crate::h3::PseudoHeaders; 29 use crate::headers::HeadersIntoIter; 30 use crate::huffman::huffman_encode; 31 32 pub struct ReprEncoder<'a> { 33 stream_id: u64, 34 base: u64, 35 is_huffman: bool, 36 table: &'a mut DynamicTable, 37 } 38 39 impl<'a> ReprEncoder<'a> { new(stream_id: u64, base: u64, is_huffman: bool, table: &'a mut DynamicTable) -> Self40 pub fn new(stream_id: u64, base: u64, is_huffman: bool, table: &'a mut DynamicTable) -> Self { 41 Self { 42 stream_id, 43 base, 44 is_huffman, 45 table, 46 } 47 } 48 get_prefix(&self, max_ref: usize, prefix_buf: &mut Vec<u8>)49 fn get_prefix(&self, max_ref: usize, prefix_buf: &mut Vec<u8>) { 50 let required_insert_count = max_ref + 1; 51 52 let mut wire_ric = 0; 53 if max_ref != 0 { 54 wire_ric = required_insert_count % (2 * self.table.max_entries()) + 1; 55 Integer::index(0x00, wire_ric, 0xff).encode(prefix_buf); 56 let base = self.base as usize; 57 if base >= required_insert_count { 58 Integer::index(0x00, base - required_insert_count, 0x7f).encode(prefix_buf); 59 } else { 60 Integer::index(0x80, required_insert_count - base - 1, 0x7f).encode(prefix_buf); 61 } 62 } else { 63 Integer::index(0x00, wire_ric, 0xff).encode(prefix_buf); 64 Integer::index(0x00, 0, 0x7f).encode(prefix_buf); 65 } 66 } 67 iterate_encode_fields( &mut self, field_iter: &mut Option<PartsIter>, track_map: &mut HashMap<u64, UnackFields>, blocked_cnt: &mut usize, allow_block: bool, fields: &mut Vec<u8>, inst: &mut Vec<u8>, )68 pub(crate) fn iterate_encode_fields( 69 &mut self, 70 field_iter: &mut Option<PartsIter>, 71 track_map: &mut HashMap<u64, UnackFields>, 72 blocked_cnt: &mut usize, 73 allow_block: bool, 74 fields: &mut Vec<u8>, 75 inst: &mut Vec<u8>, 76 ) { 77 let mut max_dynamic = 0; 78 79 let mut ref_fields = HashSet::<usize>::new(); 80 81 if let Some(mut iter) = field_iter.take() { 82 while let Some((field_h, field_v)) = iter.next() { 83 if let Some(dyn_ref) = 84 self.encode_field(&mut ref_fields, field_h, field_v, inst, fields, allow_block) 85 { 86 max_dynamic = max(max_dynamic, dyn_ref); 87 } 88 } 89 } 90 91 let enc_field_lines = mem::take(fields); 92 93 self.get_prefix(max_dynamic, fields); 94 fields.extend_from_slice(enc_field_lines.as_slice()); 95 if (max_dynamic as u64) > self.table.known_recved_count() { 96 *blocked_cnt += 1; 97 } 98 99 if !ref_fields.is_empty() { 100 track_map 101 .entry(self.stream_id) 102 .or_default() 103 .update(ref_fields); 104 } 105 } 106 encode_field( &mut self, ref_fields: &mut HashSet<usize>, field_h: NameField, field_v: String, inst: &mut Vec<u8>, fields: &mut Vec<u8>, allow_block: bool, ) -> Option<usize>107 fn encode_field( 108 &mut self, 109 ref_fields: &mut HashSet<usize>, 110 field_h: NameField, 111 field_v: String, 112 inst: &mut Vec<u8>, 113 fields: &mut Vec<u8>, 114 allow_block: bool, 115 ) -> Option<usize> { 116 let mut dynamic_index = None; 117 match self.search_filed_from_table(&field_h, field_v.as_str(), allow_block) { 118 SearchResult::StaticIndex(index) => { 119 Indexed::new(index, true).encode(fields); 120 } 121 SearchResult::StaticNameIndex(index) => { 122 IndexingWithName::new(index, field_v.into_bytes(), self.is_huffman, true, false) 123 .encode(fields); 124 } 125 SearchResult::DynamicIndex(index) => { 126 self.indexed_dynamic_field(index, fields); 127 if ref_fields.insert(index) { 128 self.table.track_field(index); 129 } 130 dynamic_index = Some(index); 131 } 132 SearchResult::DynamicNameIndex(index) => { 133 self.indexed_name_ref_with_literal_field(index, field_v, self.is_huffman, fields); 134 if ref_fields.insert(index) { 135 self.table.track_field(index) 136 } 137 dynamic_index = Some(index); 138 } 139 SearchResult::NotFound => { 140 // allow_block允许插入或引用未确认的index 141 if allow_block { 142 if let Some(index) = self.add_field_to_dynamic( 143 field_h.clone(), 144 field_v.clone(), 145 inst, 146 self.is_huffman, 147 ) { 148 self.indexed_dynamic_field(index, fields); 149 ref_fields.insert(index); 150 self.table.track_field(index); 151 dynamic_index = Some(index); 152 } else { 153 IndexingWithLiteral::new( 154 field_h.to_string().into_bytes(), 155 field_v.into_bytes(), 156 self.is_huffman, 157 false, 158 ) 159 .encode(fields); 160 } 161 } else { 162 IndexingWithLiteral::new( 163 field_h.to_string().into_bytes(), 164 field_v.into_bytes(), 165 self.is_huffman, 166 false, 167 ) 168 .encode(fields); 169 } 170 } 171 } 172 dynamic_index 173 } 174 indexed_dynamic_field(&self, index: usize, fields: &mut Vec<u8>)175 fn indexed_dynamic_field(&self, index: usize, fields: &mut Vec<u8>) { 176 if index as u64 >= self.base { 177 IndexedWithPost::new(index - (self.base as usize)).encode(fields); 178 } else { 179 Indexed::new((self.base as usize) - index - 1, false).encode(fields); 180 } 181 } 182 indexed_name_ref_with_literal_field( &self, index: usize, field_v: String, is_huffman: bool, fields: &mut Vec<u8>, )183 fn indexed_name_ref_with_literal_field( 184 &self, 185 index: usize, 186 field_v: String, 187 is_huffman: bool, 188 fields: &mut Vec<u8>, 189 ) { 190 if index as u64 >= self.base { 191 IndexingWithPostName::new( 192 index - (self.base as usize), 193 field_v.into_bytes(), 194 is_huffman, 195 false, 196 ) 197 .encode(fields); 198 } else { 199 InsertWithName::new( 200 (self.base as usize) - index - 1, 201 field_v.into_bytes(), 202 is_huffman, 203 false, 204 ) 205 .encode(fields); 206 } 207 } 208 add_field_to_dynamic( &mut self, field_h: NameField, field_v: String, inst: &mut Vec<u8>, is_huffman: bool, ) -> Option<usize>209 fn add_field_to_dynamic( 210 &mut self, 211 field_h: NameField, 212 field_v: String, 213 inst: &mut Vec<u8>, 214 is_huffman: bool, 215 ) -> Option<usize> { 216 let header_size = field_h.len() + field_v.len() + 32; 217 if let Some(len) = self.table.can_evict(header_size) { 218 InsertWithLiteral::new( 219 field_h.to_string().into_bytes(), 220 field_v.clone().into_bytes(), 221 is_huffman, 222 ) 223 .encode(inst); 224 self.table.evict_drained(len); 225 Some(self.table.update(field_h, field_v)) 226 } else { 227 IndexingWithLiteral::new( 228 field_h.to_string().into_bytes(), 229 field_v.into_bytes(), 230 is_huffman, 231 false, 232 ) 233 .encode(inst); 234 None 235 } 236 } 237 search_filed_from_table( &mut self, h: &NameField, v: &str, allow_block: bool, ) -> SearchResult238 fn search_filed_from_table( 239 &mut self, 240 h: &NameField, 241 v: &str, 242 allow_block: bool, 243 ) -> SearchResult { 244 let searcher = TableSearcher::new(self.table); 245 let mut search_result = SearchResult::NotFound; 246 match searcher.search_in_static(h, v) { 247 TableIndex::Field(index) => { 248 return SearchResult::StaticIndex(index); 249 } 250 TableIndex::FieldName(index) => { 251 search_result = SearchResult::StaticNameIndex(index); 252 } 253 TableIndex::None => {} 254 } 255 256 match searcher.search_in_dynamic(h, v, allow_block) { 257 TableIndex::Field(index) => { 258 return SearchResult::DynamicIndex(index); 259 } 260 TableIndex::FieldName(index) => { 261 if search_result == SearchResult::NotFound { 262 search_result = SearchResult::DynamicNameIndex(index); 263 } 264 } 265 TableIndex::None => {} 266 } 267 268 search_result 269 } 270 } 271 272 pub(crate) enum ReprEncodeState { 273 SetCap(SetCap), 274 Indexed(Indexed), 275 InsertWithName(InsertWithName), 276 InsertWithLiteral(InsertWithLiteral), 277 IndexingWithName(IndexingWithName), 278 IndexingWithPostName(IndexingWithPostName), 279 IndexingWithLiteral(IndexingWithLiteral), 280 IndexedWithPostName(IndexedWithPost), 281 Duplicate(Duplicate), 282 } 283 284 pub(crate) struct SetCap { 285 capacity: Integer, 286 } 287 288 impl SetCap { from(capacity: Integer) -> Self289 fn from(capacity: Integer) -> Self { 290 Self { capacity } 291 } 292 new(capacity: usize) -> Self293 pub(crate) fn new(capacity: usize) -> Self { 294 Self { 295 capacity: Integer::index(0x20, capacity, PrefixMask::SET_CAP.0), 296 } 297 } 298 encode(self, dst: &mut Vec<u8>)299 pub(crate) fn encode(self, dst: &mut Vec<u8>) { 300 self.capacity.encode(dst) 301 } 302 } 303 304 pub(crate) struct Duplicate { 305 index: Integer, 306 } 307 308 #[allow(unused)] 309 impl Duplicate { from(index: Integer) -> Self310 fn from(index: Integer) -> Self { 311 Self { index } 312 } 313 new(index: usize) -> Self314 fn new(index: usize) -> Self { 315 Self { 316 index: Integer::index(0x00, index, PrefixMask::DUPLICATE.0), 317 } 318 } 319 encode(self, dst: &mut Vec<u8>)320 fn encode(self, dst: &mut Vec<u8>) { 321 self.index.encode(dst) 322 } 323 } 324 325 pub(crate) struct Indexed { 326 index: Integer, 327 } 328 329 impl Indexed { from(index: Integer) -> Self330 fn from(index: Integer) -> Self { 331 Self { index } 332 } 333 new(index: usize, is_static: bool) -> Self334 fn new(index: usize, is_static: bool) -> Self { 335 if is_static { 336 // in static table 337 Self { 338 index: Integer::index(0xc0, index, PrefixMask::INDEXED.0), 339 } 340 } else { 341 // in dynamic table 342 Self { 343 index: Integer::index(0x80, index, PrefixMask::INDEXED.0), 344 } 345 } 346 } 347 encode(self, dst: &mut Vec<u8>)348 fn encode(self, dst: &mut Vec<u8>) { 349 self.index.encode(dst) 350 } 351 } 352 353 pub(crate) struct IndexedWithPost { 354 index: Integer, 355 } 356 357 impl IndexedWithPost { from(index: Integer) -> Self358 fn from(index: Integer) -> Self { 359 Self { index } 360 } 361 new(index: usize) -> Self362 fn new(index: usize) -> Self { 363 Self { 364 index: Integer::index(0x10, index, PrefixMask::INDEXED_WITH_POST_NAME.0), 365 } 366 } 367 encode(self, dst: &mut Vec<u8>)368 fn encode(self, dst: &mut Vec<u8>) { 369 self.index.encode(dst) 370 } 371 } 372 373 pub(crate) struct InsertWithName { 374 inner: IndexAndValue, 375 } 376 377 impl InsertWithName { from(inner: IndexAndValue) -> Self378 fn from(inner: IndexAndValue) -> Self { 379 Self { inner } 380 } 381 new(index: usize, value: Vec<u8>, is_huffman: bool, is_static: bool) -> Self382 fn new(index: usize, value: Vec<u8>, is_huffman: bool, is_static: bool) -> Self { 383 if is_static { 384 Self { 385 inner: IndexAndValue::new() 386 .set_index(0xc0, index, PrefixMask::INSERT_WITH_INDEX.0) 387 .set_value(value, is_huffman), 388 } 389 } else { 390 Self { 391 inner: IndexAndValue::new() 392 .set_index(0x80, index, PrefixMask::INSERT_WITH_INDEX.0) 393 .set_value(value, is_huffman), 394 } 395 } 396 } 397 encode(self, dst: &mut Vec<u8>)398 fn encode(self, dst: &mut Vec<u8>) { 399 self.inner.encode(dst) 400 } 401 } 402 403 pub(crate) struct IndexingWithName { 404 inner: IndexAndValue, 405 } 406 407 impl IndexingWithName { from(inner: IndexAndValue) -> Self408 fn from(inner: IndexAndValue) -> Self { 409 Self { inner } 410 } 411 new( index: usize, value: Vec<u8>, is_huffman: bool, is_static: bool, no_permit: bool, ) -> Self412 fn new( 413 index: usize, 414 value: Vec<u8>, 415 is_huffman: bool, 416 is_static: bool, 417 no_permit: bool, 418 ) -> Self { 419 match (no_permit, is_static) { 420 (true, true) => Self { 421 inner: IndexAndValue::new() 422 .set_index(0x70, index, PrefixMask::INDEXING_WITH_NAME.0) 423 .set_value(value, is_huffman), 424 }, 425 (true, false) => Self { 426 inner: IndexAndValue::new() 427 .set_index(0x60, index, PrefixMask::INDEXING_WITH_NAME.0) 428 .set_value(value, is_huffman), 429 }, 430 (false, true) => Self { 431 inner: IndexAndValue::new() 432 .set_index(0x50, index, PrefixMask::INDEXING_WITH_NAME.0) 433 .set_value(value, is_huffman), 434 }, 435 (false, false) => Self { 436 inner: IndexAndValue::new() 437 .set_index(0x40, index, PrefixMask::INDEXING_WITH_NAME.0) 438 .set_value(value, is_huffman), 439 }, 440 } 441 } 442 encode(self, dst: &mut Vec<u8>)443 fn encode(self, dst: &mut Vec<u8>) { 444 self.inner.encode(dst) 445 } 446 } 447 448 pub(crate) struct IndexingWithPostName { 449 inner: IndexAndValue, 450 } 451 452 impl IndexingWithPostName { from(inner: IndexAndValue) -> Self453 fn from(inner: IndexAndValue) -> Self { 454 Self { inner } 455 } 456 new(index: usize, value: Vec<u8>, is_huffman: bool, no_permit: bool) -> Self457 fn new(index: usize, value: Vec<u8>, is_huffman: bool, no_permit: bool) -> Self { 458 if no_permit { 459 Self { 460 inner: IndexAndValue::new() 461 .set_index(0x08, index, PrefixMask::INDEXED_WITH_POST_NAME.0) 462 .set_value(value, is_huffman), 463 } 464 } else { 465 Self { 466 inner: IndexAndValue::new() 467 .set_index(0x00, index, PrefixMask::INDEXED_WITH_POST_NAME.0) 468 .set_value(value, is_huffman), 469 } 470 } 471 } 472 encode(self, dst: &mut Vec<u8>)473 fn encode(self, dst: &mut Vec<u8>) { 474 self.inner.encode(dst) 475 } 476 } 477 478 pub(crate) struct IndexingWithLiteral { 479 inner: NameAndValue, 480 } 481 482 impl IndexingWithLiteral { new(name: Vec<u8>, value: Vec<u8>, is_huffman: bool, no_permit: bool) -> Self483 fn new(name: Vec<u8>, value: Vec<u8>, is_huffman: bool, no_permit: bool) -> Self { 484 match (no_permit, is_huffman) { 485 (true, true) => Self { 486 inner: NameAndValue::new() 487 .set_index(0x38, name.len(), PrefixMask::INSERT_WITH_LITERAL.0) 488 .set_name_and_value(name, value, is_huffman), 489 }, 490 (true, false) => Self { 491 inner: NameAndValue::new() 492 .set_index(0x30, name.len(), PrefixMask::INSERT_WITH_LITERAL.0) 493 .set_name_and_value(name, value, is_huffman), 494 }, 495 (false, true) => Self { 496 inner: NameAndValue::new() 497 .set_index(0x28, name.len(), PrefixMask::INSERT_WITH_LITERAL.0) 498 .set_name_and_value(name, value, is_huffman), 499 }, 500 (false, false) => Self { 501 inner: NameAndValue::new() 502 .set_index(0x20, name.len(), PrefixMask::INSERT_WITH_LITERAL.0) 503 .set_name_and_value(name, value, is_huffman), 504 }, 505 } 506 } 507 from(inner: NameAndValue) -> Self508 fn from(inner: NameAndValue) -> Self { 509 Self { inner } 510 } 511 encode(self, dst: &mut Vec<u8>)512 fn encode(self, dst: &mut Vec<u8>) { 513 self.inner.encode(dst) 514 } 515 } 516 517 pub(crate) struct InsertWithLiteral { 518 inner: NameAndValue, 519 } 520 521 impl InsertWithLiteral { new(name: Vec<u8>, value: Vec<u8>, is_huffman: bool) -> Self522 fn new(name: Vec<u8>, value: Vec<u8>, is_huffman: bool) -> Self { 523 if is_huffman { 524 Self { 525 inner: NameAndValue::new() 526 .set_index(0x60, name.len(), PrefixMask::INSERT_WITH_LITERAL.0) 527 .set_name_and_value(name, value, is_huffman), 528 } 529 } else { 530 Self { 531 inner: NameAndValue::new() 532 .set_index(0x40, name.len(), PrefixMask::INSERT_WITH_LITERAL.0) 533 .set_name_and_value(name, value, is_huffman), 534 } 535 } 536 } 537 from(inner: NameAndValue) -> Self538 fn from(inner: NameAndValue) -> Self { 539 Self { inner } 540 } 541 encode(self, dst: &mut Vec<u8>)542 fn encode(self, dst: &mut Vec<u8>) { 543 self.inner.encode(dst) 544 } 545 } 546 547 pub(crate) struct IndexAndValue { 548 index: Option<Integer>, 549 value_length: Option<Integer>, 550 value_octets: Option<Octets>, 551 } 552 macro_rules! check_and_encode { 553 ($item: expr, $dst: expr) => {{ 554 if let Some(i) = $item.take() { 555 i.encode($dst) 556 } 557 }}; 558 } 559 impl IndexAndValue { new() -> Self560 fn new() -> Self { 561 Self { 562 index: None, 563 value_length: None, 564 value_octets: None, 565 } 566 } 567 set_index(mut self, pre: u8, index: usize, mask: u8) -> Self568 fn set_index(mut self, pre: u8, index: usize, mask: u8) -> Self { 569 self.index = Some(Integer::index(pre, index, mask)); 570 self 571 } 572 set_value(mut self, value: Vec<u8>, is_huffman: bool) -> Self573 fn set_value(mut self, value: Vec<u8>, is_huffman: bool) -> Self { 574 let huffman_value = Octets::new(value, is_huffman); 575 self.value_length = Some(Integer::length(huffman_value.len(), is_huffman)); 576 self.value_octets = Some(huffman_value); 577 self 578 } 579 encode(mut self, dst: &mut Vec<u8>)580 fn encode(mut self, dst: &mut Vec<u8>) { 581 check_and_encode!(self.index, dst); 582 check_and_encode!(self.value_length, dst); 583 check_and_encode!(self.value_octets, dst); 584 } 585 } 586 587 pub(crate) struct NameAndValue { 588 index: Option<Integer>, 589 name_length: Option<Integer>, 590 name_octets: Option<Octets>, 591 value_length: Option<Integer>, 592 value_octets: Option<Octets>, 593 } 594 595 impl NameAndValue { new() -> Self596 fn new() -> Self { 597 Self { 598 index: None, 599 name_length: None, 600 name_octets: None, 601 value_length: None, 602 value_octets: None, 603 } 604 } 605 set_index(mut self, pre: u8, index: usize, mask: u8) -> Self606 fn set_index(mut self, pre: u8, index: usize, mask: u8) -> Self { 607 self.index = Some(Integer::index(pre, index, mask)); 608 self 609 } 610 set_name_and_value(mut self, name: Vec<u8>, value: Vec<u8>, is_huffman: bool) -> Self611 fn set_name_and_value(mut self, name: Vec<u8>, value: Vec<u8>, is_huffman: bool) -> Self { 612 let huffman_name = Octets::new(name, is_huffman); 613 self.name_length = Some(Integer::length(huffman_name.len(), is_huffman)); 614 self.name_octets = Some(huffman_name); 615 let huffman_value = Octets::new(value, is_huffman); 616 self.value_length = Some(Integer::length(huffman_value.len(), is_huffman)); 617 self.value_octets = Some(huffman_value); 618 self 619 } 620 encode(mut self, dst: &mut Vec<u8>)621 fn encode(mut self, dst: &mut Vec<u8>) { 622 check_and_encode!(self.index, dst); 623 // check_and_encode!(self.name_length, &mut dst[cur..], cur, self); //no need 624 // for qpack cause it in index. 625 check_and_encode!(self.name_octets, dst); 626 check_and_encode!(self.value_length, dst); 627 check_and_encode!(self.value_octets, dst); 628 } 629 } 630 631 macro_rules! state_def { 632 ($name: ident, $decoded: ty, $($state: ident),* $(,)?) => { 633 pub(crate) enum $name { 634 $( 635 $state($state), 636 )* 637 } 638 639 impl $name { 640 fn decode(self, buf: &mut &[u8]) -> DecResult<$decoded, $name> { 641 match self { 642 $( 643 Self::$state(state) => state.decode(buf), 644 )* 645 } 646 } 647 } 648 649 $( 650 impl From<$state> for $name { 651 fn from(s: $state) -> Self { 652 Self::$state(s) 653 } 654 } 655 )* 656 } 657 } 658 659 state_def!(InstDecodeState, DecoderInstruction, DecInstIndex); 660 pub(crate) struct DecInstDecoder<'a> { 661 buf: &'a [u8], 662 } 663 664 impl<'a> DecInstDecoder<'a> { new(buf: &'a [u8]) -> Self665 pub(crate) fn new(buf: &'a [u8]) -> Self { 666 Self { buf } 667 } 668 decode( &mut self, ins_state: &mut Option<InstDecodeState>, ) -> Result<Option<DecoderInstruction>, QpackError>669 pub(crate) fn decode( 670 &mut self, 671 ins_state: &mut Option<InstDecodeState>, 672 ) -> Result<Option<DecoderInstruction>, QpackError> { 673 if self.buf.is_empty() { 674 return Ok(None); 675 } 676 677 match ins_state 678 .take() 679 .unwrap_or_else(|| InstDecodeState::DecInstIndex(DecInstIndex::new())) 680 .decode(&mut self.buf) 681 { 682 // If `buf` is not enough to continue decoding a complete 683 // `Representation`, `Ok(None)` will be returned. Users need to call 684 // `save` to save the current state to a `ReprDecStateHolder`. 685 DecResult::NeedMore(state) => { 686 *ins_state = Some(state); 687 Ok(None) 688 } 689 DecResult::Decoded(repr) => Ok(Some(repr)), 690 691 DecResult::Error(error) => Err(error), 692 } 693 } 694 } 695 696 state_def!( 697 DecInstIndexInner, 698 (DecoderInstPrefixBit, usize), 699 InstFirstByte, 700 InstTrailingBytes 701 ); 702 703 pub(crate) struct DecInstIndex { 704 inner: DecInstIndexInner, 705 } 706 707 impl DecInstIndex { new() -> Self708 fn new() -> Self { 709 Self::from_inner(InstFirstByte.into()) 710 } from_inner(inner: DecInstIndexInner) -> Self711 fn from_inner(inner: DecInstIndexInner) -> Self { 712 Self { inner } 713 } decode(self, buf: &mut &[u8]) -> DecResult<DecoderInstruction, InstDecodeState>714 fn decode(self, buf: &mut &[u8]) -> DecResult<DecoderInstruction, InstDecodeState> { 715 match self.inner.decode(buf) { 716 DecResult::Decoded((DecoderInstPrefixBit::ACK, index)) => { 717 DecResult::Decoded(DecoderInstruction::Ack { stream_id: index }) 718 } 719 DecResult::Decoded((DecoderInstPrefixBit::STREAM_CANCEL, index)) => { 720 DecResult::Decoded(DecoderInstruction::StreamCancel { stream_id: index }) 721 } 722 DecResult::Decoded((DecoderInstPrefixBit::INSERT_COUNT_INCREMENT, index)) => { 723 DecResult::Decoded(DecoderInstruction::InsertCountIncrement { increment: index }) 724 } 725 DecResult::Error(e) => e.into(), 726 _ => DecResult::Error(QpackError::ConnectionError(DecoderStreamError)), 727 } 728 } 729 } 730 731 pub(crate) struct InstFirstByte; 732 733 impl InstFirstByte { decode( self, buf: &mut &[u8], ) -> DecResult<(DecoderInstPrefixBit, usize), DecInstIndexInner>734 fn decode( 735 self, 736 buf: &mut &[u8], 737 ) -> DecResult<(DecoderInstPrefixBit, usize), DecInstIndexInner> { 738 // If `buf` has been completely decoded here, return the current state. 739 if buf.is_empty() { 740 return DecResult::NeedMore(self.into()); 741 } 742 let byte = buf[0]; 743 let inst = DecoderInstPrefixBit::from_u8(byte); 744 let mask = inst.prefix_index_mask(); 745 746 // Moves the pointer of `buf` backward. 747 *buf = &buf[1..]; 748 match IntegerDecoder::first_byte(byte, mask.0) { 749 // Return the ReprPrefixBit and index part value. 750 Ok(idx) => DecResult::Decoded((inst, idx)), 751 // Index part value is longer than index(i.e. use all 1 to represent), so it needs more 752 // bytes to decode. 753 Err(int) => InstTrailingBytes::new(inst, int).decode(buf), 754 } 755 } 756 } 757 758 pub(crate) struct InstTrailingBytes { 759 inst: DecoderInstPrefixBit, 760 index: IntegerDecoder, 761 } 762 763 impl InstTrailingBytes { new(inst: DecoderInstPrefixBit, index: IntegerDecoder) -> Self764 fn new(inst: DecoderInstPrefixBit, index: IntegerDecoder) -> Self { 765 Self { inst, index } 766 } decode( mut self, buf: &mut &[u8], ) -> DecResult<(DecoderInstPrefixBit, usize), DecInstIndexInner>767 fn decode( 768 mut self, 769 buf: &mut &[u8], 770 ) -> DecResult<(DecoderInstPrefixBit, usize), DecInstIndexInner> { 771 loop { 772 // If `buf` has been completely decoded here, return the current state. 773 if buf.is_empty() { 774 return DecResult::NeedMore(self.into()); 775 } 776 777 let byte = buf[0]; 778 *buf = &buf[1..]; 779 // Updates trailing bytes until we get the index. 780 match self.index.next_byte(byte) { 781 Ok(None) => {} 782 Ok(Some(index)) => return DecResult::Decoded((self.inst, index)), 783 Err(e) => return e.into(), 784 } 785 } 786 } 787 } 788 789 pub(crate) struct Octets { 790 src: Vec<u8>, 791 } 792 793 impl Octets { new(src: Vec<u8>, is_huffman: bool) -> Self794 fn new(src: Vec<u8>, is_huffman: bool) -> Self { 795 if is_huffman { 796 let mut dst = Vec::with_capacity(src.len()); 797 huffman_encode(src.as_slice(), dst.as_mut()); 798 Self { src: dst } 799 } else { 800 Self { src } 801 } 802 } 803 encode(self, dst: &mut Vec<u8>)804 fn encode(self, dst: &mut Vec<u8>) { 805 dst.extend_from_slice(self.src.as_slice()); 806 } 807 len(&self) -> usize808 fn len(&self) -> usize { 809 self.src.len() 810 } 811 } 812 813 pub(crate) struct PartsIter { 814 pseudo: PseudoHeaders, 815 map: HeadersIntoIter, 816 next_type: PartsIterDirection, 817 } 818 819 /// `PartsIterDirection` is the `PartsIter`'s direction to get the next header. 820 enum PartsIterDirection { 821 Authority, 822 Method, 823 Path, 824 Scheme, 825 Status, 826 Other, 827 } 828 829 impl PartsIter { 830 /// Creates a new `PartsIter` from the given `Parts`. new(parts: Parts) -> Self831 pub(crate) fn new(parts: Parts) -> Self { 832 Self { 833 pseudo: parts.pseudo, 834 map: parts.map.into_iter(), 835 next_type: PartsIterDirection::Method, 836 } 837 } 838 839 /// Gets headers in the order of `Method`, `Status`, `Scheme`, `Path`, 840 /// `Authority` and `Other`. next(&mut self) -> Option<(NameField, String)>841 fn next(&mut self) -> Option<(NameField, String)> { 842 loop { 843 match self.next_type { 844 PartsIterDirection::Method => match self.pseudo.take_method() { 845 Some(value) => return Some((NameField::Method, value)), 846 None => self.next_type = PartsIterDirection::Status, 847 }, 848 PartsIterDirection::Status => match self.pseudo.take_status() { 849 Some(value) => return Some((NameField::Status, value)), 850 None => self.next_type = PartsIterDirection::Scheme, 851 }, 852 PartsIterDirection::Scheme => match self.pseudo.take_scheme() { 853 Some(value) => return Some((NameField::Scheme, value)), 854 None => self.next_type = PartsIterDirection::Path, 855 }, 856 PartsIterDirection::Path => match self.pseudo.take_path() { 857 Some(value) => return Some((NameField::Path, value)), 858 None => self.next_type = PartsIterDirection::Authority, 859 }, 860 PartsIterDirection::Authority => match self.pseudo.take_authority() { 861 Some(value) => return Some((NameField::Authority, value)), 862 None => self.next_type = PartsIterDirection::Other, 863 }, 864 PartsIterDirection::Other => { 865 return self 866 .map 867 .next() 868 .map(|(h, v)| (NameField::Other(h.to_string()), v.to_string().unwrap())); 869 } 870 } 871 } 872 } 873 } 874