/// This is only used by header decoder therefore all errors are `DecompressionFailed`. /// A header block is read entirely before decoding it, therefore if there is not enough /// data in the buffer an error `DecompressionFailed` will be return. pub(crate) struct ReceiverBufferWrapper<'a> {
buf: &'a [u8],
offset: usize,
}
impl ReadByte for ReceiverBufferWrapper<'_> { fn read_byte(&mutself) -> Res<u8> { ifself.offset == self.buf.len() {
Err(Error::DecompressionFailed)
} else { let b = self.buf[self.offset]; self.offset += 1;
Ok(b)
}
}
}
/// The function decodes varint with a prefixed, i.e. ignores `prefix_len` bits of the first /// byte. /// `ReceiverBufferWrapper` is only used for decoding header blocks. The header blocks are read /// entirely before a decoding starts, therefore any incomplete varint because of reaching the /// end of a buffer will be treated as the `DecompressionFailed` error. pubfn read_prefixed_int(&mutself, prefix_len: u8) -> Res<u64> {
debug_assert!(prefix_len < 8);
/// Do not use `LiteralReader` here to avoid copying data. /// The function decoded a literal with a prefix: /// 1) ignores `prefix_len` bits of the first byte, /// 2) reads "huffman bit" /// 3) decode varint that is the length of a literal /// 4) reads the literal /// 5) performs huffman decoding if needed. /// /// `ReceiverBufferWrapper` is only used for decoding header blocks. The header blocks are read /// entirely before a decoding starts, therefore any incomplete varint or literal because of /// reaching the end of a buffer will be treated as the `DecompressionFailed` error. pubfn read_literal_from_buffer(&mutself, prefix_len: u8) -> Res<String> {
debug_assert!(prefix_len < 7);
let first_byte = self.read_byte()?; let use_huffman = (first_byte & (0x80 >> prefix_len)) != 0; letmut int_reader = IntReader::new(first_byte, prefix_len + 1); let length: usize = int_reader
.read(self)?
.try_into()
.or(Err(Error::DecompressionFailed))?; if use_huffman {
Ok(parse_utf8(&decode_huffman(self.slice(length)?)?)?.to_string())
} else {
Ok(parse_utf8(self.slice(length)?)?.to_string())
}
}
/// This is varint reader that can take into account a prefix. #[derive(Debug)] pubstruct IntReader {
value: u64,
cnt: u8,
done: bool,
}
impl IntReader { /// `IntReader` is created by suppling the first byte anf prefix length. /// A varint may take only one byte, In that case already the first by has set state to done. /// /// # Panics /// /// When `prefix_len` is 8 or larger. #[must_use] pubfn new(first_byte: u8, prefix_len: u8) -> Self {
debug_assert!(prefix_len < 8, "prefix cannot larger than 7."); let mask = if prefix_len == 0 { 0xff
} else {
(1 << (8 - prefix_len)) - 1
}; let value = u64::from(first_byte & mask);
/// # Panics /// /// Never, but rust doesn't know that. #[must_use] pubfn make(first_byte: u8, prefixes: &[Prefix]) -> Self { for prefix in prefixes { if prefix.cmp_prefix(first_byte) { returnSelf::new(first_byte, prefix.len());
}
}
unreachable!();
}
/// This function reads bytes until the varint is decoded or until stream/buffer does not /// have any more date. /// /// # Errors /// /// Possible errors are: /// 1) `NeedMoreData` if the reader needs more data, /// 2) `IntegerOverflow`, /// 3) Any `ReadByte`'s error pubfn read<R: ReadByte>(&mutself, s: &mut R) -> Res<u64> { letmut b: u8; while !self.done {
b = s.read_byte()?;
/// This is decoder of a literal with a prefix: /// 1) ignores `prefix_len` bits of the first byte, /// 2) reads "huffman bit" /// 3) decode varint that is the length of a literal /// 4) reads the literal /// 5) performs huffman decoding if needed. #[derive(Debug, Default)] pubstruct LiteralReader {
state: LiteralReaderState,
literal: Vec<u8>,
use_huffman: bool,
}
impl LiteralReader { /// Creates `LiteralReader` with the first byte. This constructor is always used /// when a litreral has a prefix. /// For literals without a prefix please use the default constructor. /// /// # Panics /// /// If `prefix_len` is 8 or more. #[must_use] pubfn new_with_first_byte(first_byte: u8, prefix_len: u8) -> Self {
assert!(prefix_len < 8); Self {
state: LiteralReaderState::ReadLength {
reader: IntReader::new(first_byte, prefix_len + 1),
},
literal: Vec::new(),
use_huffman: (first_byte & (0x80 >> prefix_len)) != 0,
}
}
/// This function reads bytes until the literal is decoded or until stream/buffer does not /// have any more date ready. /// /// # Errors /// /// Possible errors are: /// 1) `NeedMoreData` if the reader needs more data, /// 2) `IntegerOverflow` /// 3) Any `ReadByte`'s error /// /// It returns value if reading the literal is done or None if it needs more data. /// /// # Panics /// /// When this object is complete. pubfn read<T: ReadByte + Reader>(&mutself, s: &mut T) -> Res<Vec<u8>> { loop {
qdebug!("state = {:?}", self.state); match &mutself.state {
LiteralReaderState::ReadHuffman => { let b = s.read_byte()?;
/// This is a helper function used only by `ReceiverBufferWrapper`, therefore it returns /// `DecompressionFailed` if any error happens. /// /// # Errors /// /// If an parsing error occurred, the function returns `BadUtf8`. pubfn parse_utf8(v: &[u8]) -> Res<&str> {
str::from_utf8(v).map_err(|_| Error::BadUtf8)
}
// data has not been received yet, reading IntReader will return Err(Error::NeedMoreData).
assert_eq!(reader.read(&mut test_receiver), Err(Error::NeedMoreData));
// Write one byte.
test_receiver.write(&buf[1..2]); // data has not been received yet, reading IntReader will return Err(Error::NeedMoreData).
assert_eq!(reader.read(&mut test_receiver), Err(Error::NeedMoreData));
// Write one byte.
test_receiver.write(&buf[2..]); // Now prefixed int is complete.
assert_eq!(reader.read(&mut test_receiver), Ok(*value));
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.