FromBytes

Trait FromBytes 

Source
pub trait FromBytes {
    type Error: FromBytesError;

    // Required methods
    fn from_bytes(bytes: &[u8]) -> Result<&Self, Self::Error>;
    fn size(&self) -> usize;
    fn as_bytes(&self) -> &[u8] ;

    // Provided method
    fn max_chunk_size() -> NonZeroUsize { ... }
}
Expand description

A trait encapsulating parsing logic.

It allows fallibly converting from and to bytes with the from_bytes and as_bytes methods, respectively.

Parsing has a few constraints to allow efficient implementations of Buffer and BuffedRead:

  • An empty slice must be valid, i.e. FromBytes::from_bytes(&[]) may not return an error.
  • Valid data must be composed of individual chunks whose place relative to other chunks does not influence its validity. That is, if a and b are both valid byte sequences, ab and ba must both be too.
  • A chunk of valid data must have a known maximum size. That is, if a chunk of bytes is large enough, but still smaller than or equal to a statically known constant, it may contain any chunk of valid data that is not a repetition of smaller valid chunks. This constant is returned by the max_chunk_size method.

This is a big limitation of buffed’s parsing that makes it useful pretty much only for low-level decoding (e.g. text formats like utf8, network packets, etc.). Notably, it doesn’t allow parsing more complex syntaxes like JSON. In the future, the rule may be loosened so that more formats/types can be parsed.

Required Associated Types§

Source

type Error: FromBytesError

The error type returned by from_bytes when invalid data is encountered.

Required Methods§

Source

fn from_bytes(bytes: &[u8]) -> Result<&Self, Self::Error>

Parse some bytes and reinterprete them as this type.

§Error

If any byte sequence is invalid in bytes, a Self::Error implementing FromBytesError is returned instead.

Source

fn size(&self) -> usize

Get the size, in bytes, of self.

Source

fn as_bytes(&self) -> &[u8]

Return the byte representation of self.

Provided Methods§

Source

fn max_chunk_size() -> NonZeroUsize

Return the size of the largest chunk of valid data that is not a sequence of smaller valid chunk.

This value may be very important for Buffer and BuffedRead implementations, that may rely on it to tell when to stop buffering or whether a chunk may be incomplete (and may need fetching more data).

For instance, <str as FromBytes>::max_chunk_size() is 4, because the longest UTF8 codepoint is 4-bytes long.

The default implementation returns 1.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl FromBytes for str

Source§

impl FromBytes for [u8]

Source§

type Error = Infallible

Source§

fn from_bytes(bytes: &[u8]) -> Result<&[u8], Infallible>

Source§

fn size(&self) -> usize

Source§

fn as_bytes(&self) -> &[u8]

Implementors§