barse/from_reader/
from_reader_slice.rs

1use std::{borrow::Cow, fmt::Debug, marker::PhantomData};
2
3use bytesize::ByteSize;
4
5use crate::{error::Error, ByteRead, FromByteReader};
6
7/// Trait to query the size in bytes of something.
8pub trait ByteSizeQuery {
9    /// Type of input to use for query.
10    type Flag;
11    /// Query the input returning a size.
12    fn size(flag: &Self::Flag) -> usize;
13}
14
15/// An array of bytes with a queried length.
16#[derive(PartialEq, Eq)]
17pub struct ByteSlice<'input, Q>(Cow<'input, [u8]>, PhantomData<Q>);
18
19impl<'input, Q> FromByteReader<'input> for ByteSlice<'input, Q>
20where
21    Q: ByteSizeQuery + 'static,
22{
23    type Err = Error;
24
25    fn from_byte_reader<R>(mut reader: R) -> Result<Self, Error>
26    where
27        R: ByteRead<'input>,
28    {
29        let flag = reader.flag::<Q::Flag>()?;
30
31        Ok(Self(
32            Cow::Borrowed(reader.read_ref(Q::size(flag))?),
33            PhantomData::default(),
34        ))
35    }
36}
37
38impl<Q> AsRef<[u8]> for ByteSlice<'_, Q> {
39    fn as_ref(&self) -> &[u8] {
40        &self.0
41    }
42}
43
44impl<Q> From<ByteSlice<'_, Q>> for Vec<u8> {
45    fn from(value: ByteSlice<'_, Q>) -> Self {
46        value.0.into()
47    }
48}
49
50impl<Q> Debug for ByteSlice<'_, Q> {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        write!(f, "FromReaderSlice({})", ByteSize::b(self.0.len() as u64))
53    }
54}