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::qpack::error::ErrorCode::DecompressionFailed; 17 use crate::h3::qpack::error::{ErrorCode, H3errorQpack}; 18 use crate::h3::qpack::format::decoder::DecResult::Error; 19 use crate::h3::qpack::integer::IntegerDecoder; 20 use crate::h3::qpack::{ 21 DeltaBase, EncoderInstPrefixBit, EncoderInstruction, MidBit, PrefixMask, ReprPrefixBit, 22 Representation, RequireInsertCount, 23 }; 24 use crate::huffman::HuffmanDecoder; 25 use std::cmp::Ordering; 26 use std::marker::PhantomData; 27 28 pub(crate) struct EncInstDecoder; 29 30 impl EncInstDecoder { new() -> Self31 pub(crate) fn new() -> Self { 32 Self {} 33 } 34 35 /// Decodes `buf`. Every time users call `decode`, it will try to 36 /// decode a `EncoderInstruction`. 37 /// # Example 38 // ```no_run 39 // use crate::h3::qpack::format::decoder::EncInstDecoder; 40 // let mut decoder = EncInstDecoder::new(); 41 // 42 // ``` decode( &mut self, buf: &[u8], inst_state: &mut Option<InstDecodeState>, ) -> Result<Option<(usize, EncoderInstruction)>, H3errorQpack>43 pub(crate) fn decode( 44 &mut self, 45 buf: &[u8], 46 inst_state: &mut Option<InstDecodeState>, 47 ) -> Result<Option<(usize, EncoderInstruction)>, H3errorQpack> { 48 if buf.is_empty() { 49 return Ok(None); 50 } 51 52 match inst_state 53 .take() 54 .unwrap_or_else(|| InstDecodeState::EncInstIndex(EncInstIndex::new())) 55 .decode(buf) 56 { 57 // If `buf` is not enough to continue decoding a complete 58 // `Representation`, `Ok(None)` will be returned. Users need to call 59 // `save` to save the current state to a `ReprDecStateHolder`. 60 DecResult::NeedMore(state) => { 61 println!("need more"); 62 *inst_state = Some(state); 63 Ok(None) 64 } 65 DecResult::Decoded((buf_index, repr)) => Ok(Some((buf_index, repr))), 66 67 DecResult::Error(error) => Err(error), 68 } 69 } 70 } 71 72 pub(crate) struct ReprDecoder; 73 74 impl ReprDecoder { 75 /// Creates a new `ReprDecoder` whose `state` is `None`. new() -> Self76 pub(crate) fn new() -> Self { 77 Self {} 78 } 79 80 /// Decodes `self.buf`. Every time users call `decode`, it will try to 81 /// decode a `Representation`. decode( &mut self, buf: &[u8], repr_state: &mut Option<ReprDecodeState>, ) -> Result<Option<(usize, Representation)>, H3errorQpack>82 pub(crate) fn decode( 83 &mut self, 84 buf: &[u8], 85 repr_state: &mut Option<ReprDecodeState>, 86 ) -> Result<Option<(usize, Representation)>, H3errorQpack> { 87 // If buf is empty, leave the state unchanged. 88 let buf_len = buf.len(); 89 if buf.is_empty() { 90 return Ok(None); 91 } 92 match repr_state 93 .take() 94 .unwrap_or_else(|| ReprDecodeState::FiledSectionPrefix(FiledSectionPrefix::new())) 95 .decode(buf) 96 { 97 // If `buf` is not enough to continue decoding a complete 98 // `Representation`, `Ok(None)` will be returned. Users need to call 99 // `save` to save the current state to a `ReprDecStateHolder`. 100 DecResult::NeedMore(state) => { 101 println!("need more"); 102 *repr_state = Some(state); 103 Ok(None) 104 } 105 DecResult::Decoded((buf_index, repr)) => { 106 if buf_index >= buf_len { 107 return Ok(Some((buf_index, repr))); 108 } 109 *repr_state = Some(ReprDecodeState::ReprIndex(ReprIndex::new())); 110 Ok(Some((buf_index, repr))) 111 } 112 113 DecResult::Error(error) => Err(error), 114 } 115 } 116 } 117 macro_rules! return_res { 118 ($res: expr ,$buf_index: expr) => { 119 if let DecResult::Decoded((cnt, repr)) = $res { 120 return DecResult::Decoded((cnt + $buf_index, repr)); 121 } else { 122 $res 123 } 124 }; 125 } 126 127 macro_rules! state_def { 128 ($name: ident, $decoded: ty, $($state: ident),* $(,)?) => { 129 pub(crate) enum $name { 130 $( 131 $state($state), 132 )* 133 } 134 135 impl $name { 136 fn decode(self, buf: & [u8]) -> DecResult<$decoded, $name> { 137 match self { 138 $( 139 Self::$state(state) => state.decode(buf), 140 )* 141 } 142 } 143 } 144 145 $( 146 impl From<$state> for $name { 147 fn from(s: $state) -> Self { 148 Self::$state(s) 149 } 150 } 151 )* 152 } 153 } 154 155 state_def!( 156 FSPInner, 157 (usize, RequireInsertCount, bool, DeltaBase), 158 FSPTwoIntergers, 159 ); 160 state_def!( 161 InstDecodeState, 162 (usize, EncoderInstruction), 163 EncInstIndex, 164 InstValueString, 165 InstNameAndValue, 166 ); 167 168 state_def!( 169 ReprDecodeState, 170 (usize, Representation), 171 FiledSectionPrefix, 172 ReprIndex, 173 ReprValueString, 174 ReprNameAndValue, 175 ); 176 state_def!( 177 InstIndexInner, 178 (usize, EncoderInstPrefixBit, MidBit, usize), 179 InstFirstByte, 180 InstTrailingBytes 181 ); 182 state_def!( 183 ReprIndexInner, 184 (usize, ReprPrefixBit, MidBit, usize), 185 ReprFirstByte, 186 ReprTrailingBytes 187 ); 188 189 state_def!( 190 LiteralString, 191 (usize, Vec<u8>), 192 LengthFirstByte, 193 LengthTrailingBytes, 194 AsciiStringBytes, 195 HuffmanStringBytes, 196 ); 197 198 pub(crate) struct FiledSectionPrefix { 199 inner: FSPInner, 200 } 201 202 impl FiledSectionPrefix { new() -> Self203 fn new() -> Self { 204 Self::from_inner(FSPTwoIntergers.into()) 205 } from_inner(inner: FSPInner) -> Self206 fn from_inner(inner: FSPInner) -> Self { 207 Self { inner } 208 } 209 decode(self, buf: &[u8]) -> DecResult<(usize, Representation), ReprDecodeState>210 fn decode(self, buf: &[u8]) -> DecResult<(usize, Representation), ReprDecodeState> { 211 match self.inner.decode(buf) { 212 DecResult::Decoded((buf_index, ric, signal, delta_base)) => DecResult::Decoded(( 213 buf_index, 214 Representation::FieldSectionPrefix { 215 require_insert_count: ric, 216 signal, 217 delta_base, 218 }, 219 )), 220 DecResult::NeedMore(inner) => { 221 DecResult::NeedMore(FiledSectionPrefix::from_inner(inner).into()) 222 } 223 DecResult::Error(e) => e.into(), 224 } 225 } 226 } 227 228 pub(crate) struct EncInstIndex { 229 inner: InstIndexInner, 230 } 231 232 impl EncInstIndex { new() -> Self233 fn new() -> Self { 234 Self::from_inner(InstFirstByte.into()) 235 } from_inner(inner: InstIndexInner) -> Self236 fn from_inner(inner: InstIndexInner) -> Self { 237 Self { inner } 238 } decode(self, buf: &[u8]) -> DecResult<(usize, EncoderInstruction), InstDecodeState>239 fn decode(self, buf: &[u8]) -> DecResult<(usize, EncoderInstruction), InstDecodeState> { 240 match self.inner.decode(buf) { 241 DecResult::Decoded((buf_index, EncoderInstPrefixBit::SETCAP, _, index)) => { 242 DecResult::Decoded((buf_index, EncoderInstruction::SetCap { capacity: index })) 243 } 244 DecResult::Decoded(( 245 buf_index, 246 EncoderInstPrefixBit::INSERTWITHINDEX, 247 mid_bit, 248 index, 249 )) => { 250 let res = InstValueString::new( 251 EncoderInstPrefixBit::INSERTWITHINDEX, 252 mid_bit, 253 Name::Index(index), 254 ) 255 .decode(&buf[buf_index..]); 256 return_res!(res, buf_index) 257 } 258 DecResult::Decoded(( 259 buf_index, 260 EncoderInstPrefixBit::INSERTWITHLITERAL, 261 mid_bit, 262 namelen, 263 )) => { 264 let res = InstNameAndValue::new( 265 EncoderInstPrefixBit::INSERTWITHLITERAL, 266 mid_bit, 267 namelen, 268 ) 269 .decode(&buf[buf_index..]); 270 return_res!(res, buf_index) 271 } 272 DecResult::Decoded((remain_buf, EncoderInstPrefixBit::DUPLICATE, _, index)) => { 273 DecResult::Decoded((remain_buf, EncoderInstruction::Duplicate { index })) 274 } 275 DecResult::NeedMore(inner) => { 276 DecResult::NeedMore(EncInstIndex::from_inner(inner).into()) 277 } 278 DecResult::Error(e) => e.into(), 279 _ => DecResult::Error(H3errorQpack::ConnectionError( 280 ErrorCode::DecompressionFailed, 281 )), 282 } 283 } 284 } 285 286 pub(crate) struct ReprIndex { 287 inner: ReprIndexInner, 288 } 289 290 impl ReprIndex { new() -> Self291 fn new() -> Self { 292 Self::from_inner(ReprFirstByte.into()) 293 } from_inner(inner: ReprIndexInner) -> Self294 fn from_inner(inner: ReprIndexInner) -> Self { 295 Self { inner } 296 } decode(self, buf: &[u8]) -> DecResult<(usize, Representation), ReprDecodeState>297 fn decode(self, buf: &[u8]) -> DecResult<(usize, Representation), ReprDecodeState> { 298 match self.inner.decode(buf) { 299 DecResult::Decoded((buf_index, ReprPrefixBit::INDEXED, mid_bit, index)) => { 300 DecResult::Decoded((buf_index, Representation::Indexed { mid_bit, index })) 301 } 302 DecResult::Decoded((buf_index, ReprPrefixBit::INDEXEDWITHPOSTINDEX, _, index)) => { 303 DecResult::Decoded((buf_index, Representation::IndexedWithPostIndex { index })) 304 } 305 DecResult::Decoded((buf_index, ReprPrefixBit::LITERALWITHINDEXING, mid_bit, index)) => { 306 let res = ReprValueString::new( 307 ReprPrefixBit::LITERALWITHINDEXING, 308 mid_bit, 309 Name::Index(index), 310 ) 311 .decode(&buf[buf_index..]); 312 return_res!(res, buf_index) 313 } 314 DecResult::Decoded(( 315 buf_index, 316 ReprPrefixBit::LITERALWITHPOSTINDEXING, 317 mid_bit, 318 index, 319 )) => { 320 let res = ReprValueString::new( 321 ReprPrefixBit::LITERALWITHPOSTINDEXING, 322 mid_bit, 323 Name::Index(index), 324 ) 325 .decode(&buf[buf_index..]); 326 return_res!(res, buf_index) 327 } 328 DecResult::Decoded(( 329 buf_index, 330 ReprPrefixBit::LITERALWITHLITERALNAME, 331 mid_bit, 332 namelen, 333 )) => { 334 let res = 335 ReprNameAndValue::new(ReprPrefixBit::LITERALWITHLITERALNAME, mid_bit, namelen) 336 .decode(&buf[buf_index..]); 337 return_res!(res, buf_index) 338 } 339 DecResult::NeedMore(inner) => DecResult::NeedMore(ReprIndex::from_inner(inner).into()), 340 DecResult::Error(e) => e.into(), 341 _ => DecResult::Error(H3errorQpack::ConnectionError( 342 ErrorCode::DecompressionFailed, 343 )), 344 } 345 } 346 } 347 348 pub(crate) struct FSPTwoIntergers; 349 350 impl FSPTwoIntergers { decode( self, buf: &[u8], ) -> DecResult<(usize, RequireInsertCount, bool, DeltaBase), FSPInner>351 fn decode( 352 self, 353 buf: &[u8], 354 ) -> DecResult<(usize, RequireInsertCount, bool, DeltaBase), FSPInner> { 355 let mut buf_index = 1; 356 if buf.is_empty() { 357 return DecResult::NeedMore(self.into()); 358 } 359 let buf_len = buf.len(); 360 let mask = PrefixMask::REQUIREINSERTCOUNT; 361 let ric = match IntegerDecoder::first_byte(buf[buf_index - 1], mask.0) { 362 Ok(ric) => ric, 363 Err(mut int) => { 364 let res: usize; 365 366 loop { 367 // If `buf` has been completely decoded here, return the current state. 368 buf_index += 1; 369 if buf_index >= buf_len { 370 return DecResult::NeedMore(self.into()); 371 } 372 // Updates trailing bytes until we get the index. 373 match int.next_byte(buf[buf_index - 1]) { 374 Ok(None) => {} 375 Ok(Some(index)) => { 376 res = index; 377 break; 378 } 379 Err(e) => return e.into(), 380 } 381 } 382 res 383 } 384 }; 385 buf_index += 1; 386 if buf_index >= buf_len { 387 return DecResult::NeedMore(self.into()); 388 } 389 let byte = buf[buf_index - 1]; 390 let signal = (byte & 0x80) != 0; 391 let mask = PrefixMask::DELTABASE; 392 let delta_base = match IntegerDecoder::first_byte(byte, mask.0) { 393 Ok(delta_base) => delta_base, 394 Err(mut int) => { 395 let res: usize; 396 loop { 397 // If `buf` has been completely decoded here, return the current state. 398 buf_index += 1; 399 if buf_index >= buf_len { 400 return DecResult::NeedMore(self.into()); 401 } 402 403 // Updates trailing bytes until we get the index. 404 match int.next_byte(buf[buf_index - 1]) { 405 Ok(None) => {} 406 Ok(Some(index)) => { 407 res = index; 408 break; 409 } 410 Err(e) => return e.into(), 411 } 412 } 413 res 414 } 415 }; 416 417 DecResult::Decoded(( 418 buf_index, 419 RequireInsertCount(ric), 420 signal, 421 DeltaBase(delta_base), 422 )) 423 } 424 } 425 426 macro_rules! decode_first_byte { 427 ($struct_name:ident, $prefix_type:ty, $inner_type:ty,$trailing_bytes:ty) => { 428 pub(crate) struct $struct_name; 429 430 impl $struct_name { 431 fn decode( 432 self, 433 buf: &[u8], 434 ) -> DecResult<(usize, $prefix_type, MidBit, usize), $inner_type> { 435 // If `buf` has been completely decoded here, return the current state. 436 let buf_index = 1; 437 if buf.is_empty() { 438 return DecResult::NeedMore(self.into()); 439 } 440 441 let prefix = <$prefix_type>::from_u8(buf[buf_index - 1]); 442 let mid_bit = prefix.prefix_midbit_value(buf[buf_index - 1]); 443 let mask = prefix.prefix_index_mask(); 444 445 match IntegerDecoder::first_byte(buf[buf_index - 1], mask.0) { 446 // Return the PrefixBit and index part value. 447 Ok(idx) => DecResult::Decoded((buf_index, prefix, mid_bit, idx)), 448 // Index part value is longer than index(i.e. use all 1 to represent), so it needs more bytes to decode. 449 Err(int) => { 450 let res = 451 <$trailing_bytes>::new(prefix, mid_bit, int).decode(&buf[buf_index..]); 452 if let DecResult::Decoded((cnt, prefix, mid_bit, int)) = res { 453 return DecResult::Decoded((cnt + buf_index, prefix, mid_bit, int)); 454 } else { 455 return res; 456 } 457 } 458 } 459 } 460 } 461 }; 462 } 463 464 decode_first_byte!( 465 InstFirstByte, 466 EncoderInstPrefixBit, 467 InstIndexInner, 468 InstTrailingBytes 469 ); 470 decode_first_byte!( 471 ReprFirstByte, 472 ReprPrefixBit, 473 ReprIndexInner, 474 ReprTrailingBytes 475 ); 476 477 macro_rules! trailing_bytes_decoder { 478 ($struct_name:ident, $prefix_type:ty, $inner_type:ty) => { 479 pub(crate) struct $struct_name { 480 prefix: $prefix_type, 481 mid_bit: MidBit, 482 index: IntegerDecoder, 483 } 484 485 impl $struct_name { 486 fn new(prefix: $prefix_type, mid_bit: MidBit, index: IntegerDecoder) -> Self { 487 Self { 488 prefix, 489 mid_bit, 490 index, 491 } 492 } 493 494 fn decode( 495 mut self, 496 buf: &[u8], 497 ) -> DecResult<(usize, $prefix_type, MidBit, usize), $inner_type> { 498 let mut buf_index = 1; 499 let buf_len = buf.len(); 500 loop { 501 // If `buf` has been completely decoded here, return the current state. 502 if buf_index > buf_len { 503 return DecResult::NeedMore(self.into()); 504 } 505 506 // Updates trailing bytes until we get the index. 507 match self.index.next_byte(buf[buf_index - 1]) { 508 Ok(None) => {} 509 Ok(Some(index)) => { 510 return DecResult::Decoded(( 511 buf_index, 512 self.prefix, 513 self.mid_bit, 514 index, 515 )); 516 } 517 Err(e) => return e.into(), 518 } 519 buf_index += 1; 520 } 521 } 522 } 523 }; 524 } 525 526 trailing_bytes_decoder!(InstTrailingBytes, EncoderInstPrefixBit, InstIndexInner); 527 trailing_bytes_decoder!(ReprTrailingBytes, ReprPrefixBit, ReprIndexInner); 528 529 pub(crate) struct LengthTrailingBytes { 530 is_huffman: bool, 531 length: IntegerDecoder, 532 } 533 534 impl LengthTrailingBytes { new(is_huffman: bool, length: IntegerDecoder) -> Self535 fn new(is_huffman: bool, length: IntegerDecoder) -> Self { 536 Self { is_huffman, length } 537 } 538 decode(mut self, buf: &[u8]) -> DecResult<(usize, Vec<u8>), LiteralString>539 fn decode(mut self, buf: &[u8]) -> DecResult<(usize, Vec<u8>), LiteralString> { 540 let mut buf_index = 1; 541 let buf_len = buf.len(); 542 loop { 543 if buf_index >= buf_len { 544 return DecResult::NeedMore(self.into()); 545 } 546 547 match (self.length.next_byte(buf[buf_index - 1]), self.is_huffman) { 548 (Ok(None), _) => {} 549 (Err(e), _) => return e.into(), 550 (Ok(Some(length)), true) => { 551 let res = HuffmanStringBytes::new(length).decode(&buf[buf_index..]); 552 if let DecResult::Decoded((cnt, vec)) = res { 553 return DecResult::Decoded((cnt + buf_index, vec)); 554 } else { 555 return res; 556 } 557 } 558 (Ok(Some(length)), false) => { 559 let res = AsciiStringBytes::new(length).decode(&buf[buf_index..]); 560 if let DecResult::Decoded((cnt, vec)) = res { 561 return DecResult::Decoded((cnt + buf_index, vec)); 562 } else { 563 return res; 564 } 565 } 566 } 567 buf_index += 1; 568 } 569 } 570 } 571 572 pub(crate) struct AsciiStringBytes { 573 octets: Vec<u8>, 574 length: usize, 575 } 576 577 impl AsciiStringBytes { new(length: usize) -> Self578 fn new(length: usize) -> Self { 579 Self { 580 octets: Vec::new(), 581 length, 582 } 583 } 584 decode(mut self, buf: &[u8]) -> DecResult<(usize, Vec<u8>), LiteralString>585 fn decode(mut self, buf: &[u8]) -> DecResult<(usize, Vec<u8>), LiteralString> { 586 match (buf.len() + self.octets.len()).cmp(&self.length) { 587 Ordering::Greater | Ordering::Equal => { 588 let pos = self.length - self.octets.len(); 589 self.octets.extend_from_slice(&buf[..pos]); 590 DecResult::Decoded((pos, self.octets)) 591 } 592 Ordering::Less => { 593 self.octets.extend_from_slice(buf); 594 // let (_, mut remain_buf) = buf.split_at_mut(buf.len()); 595 DecResult::NeedMore(self.into()) 596 } 597 } 598 } 599 } 600 601 macro_rules! name_and_value_decoder { 602 ($struct_name:ident, $prefix_type:ty, $inner_type:ty, $output_type:ty, $state_type:ty,$value_string:ty) => { 603 pub(crate) struct $struct_name { 604 prefix: $prefix_type, 605 mid_bit: MidBit, 606 inner: $inner_type, 607 } 608 609 impl $struct_name { 610 fn new(prefix: $prefix_type, mid_bit: MidBit, namelen: usize) -> Self { 611 Self::from_inner(prefix, mid_bit, AsciiStringBytes::new(namelen).into()) 612 } 613 614 fn from_inner(prefix: $prefix_type, mid_bit: MidBit, inner: $inner_type) -> Self { 615 Self { 616 prefix, 617 mid_bit, 618 inner, 619 } 620 } 621 622 fn decode(self, buf: &[u8]) -> DecResult<(usize, $output_type), $state_type> { 623 match self.inner.decode(buf) { 624 DecResult::Decoded((buf_index, octets)) => { 625 let res = 626 <$value_string>::new(self.prefix, self.mid_bit, Name::Literal(octets)) 627 .decode(&buf[buf_index..]); 628 return_res!(res, buf_index) 629 } 630 DecResult::NeedMore(inner) => DecResult::NeedMore( 631 Self::from_inner(self.prefix, self.mid_bit, inner).into(), 632 ), 633 DecResult::Error(e) => e.into(), 634 } 635 } 636 } 637 }; 638 } 639 640 name_and_value_decoder!( 641 InstNameAndValue, 642 EncoderInstPrefixBit, 643 LiteralString, 644 EncoderInstruction, 645 InstDecodeState, 646 InstValueString 647 ); 648 name_and_value_decoder!( 649 ReprNameAndValue, 650 ReprPrefixBit, 651 LiteralString, 652 Representation, 653 ReprDecodeState, 654 ReprValueString 655 ); 656 657 pub(crate) struct LengthFirstByte; 658 659 impl LengthFirstByte { decode(self, buf: &[u8]) -> DecResult<(usize, Vec<u8>), LiteralString>660 fn decode(self, buf: &[u8]) -> DecResult<(usize, Vec<u8>), LiteralString> { 661 let buf_index = 1; 662 if buf.is_empty() { 663 return DecResult::NeedMore(self.into()); 664 } 665 666 match ( 667 IntegerDecoder::first_byte(buf[buf_index - 1], 0x7f), 668 (buf[buf_index - 1] & 0x80) == 0x80, 669 ) { 670 (Ok(len), true) => { 671 let res = HuffmanStringBytes::new(len).decode(&buf[buf_index..]); 672 return_res!(res, buf_index) 673 } 674 (Ok(len), false) => { 675 let res = AsciiStringBytes::new(len).decode(&buf[buf_index..]); 676 return_res!(res, buf_index) 677 } 678 (Err(int), huffman) => { 679 let res = LengthTrailingBytes::new(huffman, int).decode(&buf[buf_index..]); 680 return_res!(res, buf_index) 681 } 682 } 683 } 684 } 685 686 pub(crate) struct HuffmanStringBytes { 687 huffman: HuffmanDecoder, 688 read: usize, 689 length: usize, 690 } 691 692 impl HuffmanStringBytes { new(length: usize) -> Self693 fn new(length: usize) -> Self { 694 Self { 695 huffman: HuffmanDecoder::new(), 696 read: 0, 697 length, 698 } 699 } 700 decode(mut self, buf: &[u8]) -> DecResult<(usize, Vec<u8>), LiteralString>701 fn decode(mut self, buf: &[u8]) -> DecResult<(usize, Vec<u8>), LiteralString> { 702 match (buf.len() + self.read).cmp(&self.length) { 703 Ordering::Greater | Ordering::Equal => { 704 let pos = self.length - self.read; 705 if self.huffman.decode(&buf[..pos]).is_err() { 706 return H3errorQpack::ConnectionError(DecompressionFailed).into(); 707 } 708 // let (_, mut remain_buf) = buf.split_at_mut(pos); 709 match self.huffman.finish() { 710 Ok(vec) => DecResult::Decoded((pos, vec)), 711 Err(_) => H3errorQpack::ConnectionError(DecompressionFailed).into(), 712 } 713 } 714 Ordering::Less => { 715 if self.huffman.decode(buf).is_err() { 716 return H3errorQpack::ConnectionError(DecompressionFailed).into(); 717 } 718 self.read += buf.len(); 719 // let (_, mut remain_buf) = buf.split_at_mut(buf.len()); 720 DecResult::NeedMore(self.into()) 721 } 722 } 723 } 724 } 725 726 #[derive(Clone)] 727 pub(crate) enum Name { 728 Index(usize), 729 Literal(Vec<u8>), 730 } 731 732 pub(crate) struct InstValueString { 733 inst: EncoderInstPrefixBit, 734 mid_bit: MidBit, 735 name: Name, 736 inner: LiteralString, 737 } 738 739 impl InstValueString { new(inst: EncoderInstPrefixBit, mid_bit: MidBit, name: Name) -> Self740 fn new(inst: EncoderInstPrefixBit, mid_bit: MidBit, name: Name) -> Self { 741 Self::from_inner(inst, mid_bit, name, LengthFirstByte.into()) 742 } 743 from_inner( inst: EncoderInstPrefixBit, mid_bit: MidBit, name: Name, inner: LiteralString, ) -> Self744 fn from_inner( 745 inst: EncoderInstPrefixBit, 746 mid_bit: MidBit, 747 name: Name, 748 inner: LiteralString, 749 ) -> Self { 750 Self { 751 inst, 752 mid_bit, 753 name, 754 inner, 755 } 756 } 757 decode(self, buf: &[u8]) -> DecResult<(usize, EncoderInstruction), InstDecodeState>758 fn decode(self, buf: &[u8]) -> DecResult<(usize, EncoderInstruction), InstDecodeState> { 759 match (self.inst, self.inner.decode(buf)) { 760 (EncoderInstPrefixBit::INSERTWITHINDEX, DecResult::Decoded((buf_index, value))) => { 761 DecResult::Decoded(( 762 buf_index, 763 EncoderInstruction::InsertWithIndex { 764 mid_bit: self.mid_bit, 765 name: self.name, 766 value, 767 }, 768 )) 769 } 770 (EncoderInstPrefixBit::INSERTWITHLITERAL, DecResult::Decoded((buf_index, value))) => { 771 DecResult::Decoded(( 772 buf_index, 773 EncoderInstruction::InsertWithLiteral { 774 mid_bit: self.mid_bit, 775 name: self.name, 776 value, 777 }, 778 )) 779 } 780 (_, _) => Error(H3errorQpack::ConnectionError(DecompressionFailed)), 781 } 782 } 783 } 784 785 pub(crate) struct ReprValueString { 786 repr: ReprPrefixBit, 787 mid_bit: MidBit, 788 name: Name, 789 inner: LiteralString, 790 } 791 792 impl ReprValueString { new(repr: ReprPrefixBit, mid_bit: MidBit, name: Name) -> Self793 fn new(repr: ReprPrefixBit, mid_bit: MidBit, name: Name) -> Self { 794 Self::from_inner(repr, mid_bit, name, LengthFirstByte.into()) 795 } 796 from_inner(repr: ReprPrefixBit, mid_bit: MidBit, name: Name, inner: LiteralString) -> Self797 fn from_inner(repr: ReprPrefixBit, mid_bit: MidBit, name: Name, inner: LiteralString) -> Self { 798 Self { 799 repr, 800 mid_bit, 801 name, 802 inner, 803 } 804 } 805 decode(self, buf: &[u8]) -> DecResult<(usize, Representation), ReprDecodeState>806 fn decode(self, buf: &[u8]) -> DecResult<(usize, Representation), ReprDecodeState> { 807 match (self.repr, self.inner.decode(buf)) { 808 (ReprPrefixBit::LITERALWITHINDEXING, DecResult::Decoded((buf_index, value))) => { 809 DecResult::Decoded(( 810 buf_index, 811 Representation::LiteralWithIndexing { 812 mid_bit: self.mid_bit, 813 name: self.name, 814 value, 815 }, 816 )) 817 } 818 (ReprPrefixBit::LITERALWITHPOSTINDEXING, DecResult::Decoded((buf_index, value))) => { 819 DecResult::Decoded(( 820 buf_index, 821 Representation::LiteralWithPostIndexing { 822 mid_bit: self.mid_bit, 823 name: self.name, 824 value, 825 }, 826 )) 827 } 828 (ReprPrefixBit::LITERALWITHLITERALNAME, DecResult::Decoded((buf_index, value))) => { 829 DecResult::Decoded(( 830 buf_index, 831 Representation::LiteralWithLiteralName { 832 mid_bit: self.mid_bit, 833 name: self.name, 834 value, 835 }, 836 )) 837 } 838 (_, _) => Error(H3errorQpack::ConnectionError(DecompressionFailed)), 839 } 840 } 841 } 842 843 /// Decoder's possible returns during the decoding process. 844 pub(crate) enum DecResult<D, S> { 845 /// Decoder has got a `D`. Users can continue to call `encode` to try to 846 /// get the next `D`. 847 Decoded(D), 848 849 /// Decoder needs more bytes to decode to get a `D`. Returns the current 850 /// decoding state `S`. 851 NeedMore(S), 852 853 /// Errors that may occur when decoding. 854 Error(H3errorQpack), 855 } 856 857 impl<D, S> From<H3errorQpack> for DecResult<D, S> { from(e: H3errorQpack) -> Self858 fn from(e: H3errorQpack) -> Self { 859 DecResult::Error(e) 860 } 861 } 862