Skip to main content

ToBitStream

Trait ToBitStream 

Source
pub trait ToBitStream {
    type Error;

    // Required method
    fn to_writer<W: BitWrite + ?Sized>(
        &self,
        w: &mut W,
    ) -> Result<(), Self::Error>
       where Self: Sized;

    // Provided methods
    fn bits<C: Counter>(&self) -> Result<C, Self::Error>
       where Self: Sized { ... }
    fn bits_len<C: Counter, E: Endianness>(&self) -> Result<C, Self::Error>
       where Self: Sized { ... }
}
Expand description

Implemented by complex types that don’t require any additional context to build themselves to a writer

§Example

use std::io::Read;
use bitstream_io::{BigEndian, BitWrite, BitWriter, ToBitStream};

#[derive(Debug, PartialEq, Eq)]
struct BlockHeader {
    last_block: bool,
    block_type: u8,
    block_size: u32,
}

impl ToBitStream for BlockHeader {
    type Error = std::io::Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> std::io::Result<()> {
        w.write_bit(self.last_block)?;
        w.write::<7, _>(self.block_type)?;
        w.write::<24, _>(self.block_size)
    }
}

let mut data = Vec::new();
let mut writer = BitWriter::endian(&mut data, BigEndian);
writer.build(&BlockHeader { last_block: false, block_type: 4, block_size: 122 }).unwrap();
assert_eq!(data, b"\x04\x00\x00\x7A");

Required Associated Types§

Source

type Error

Error generated during building, such as io::Error

Required Methods§

Source

fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error>
where Self: Sized,

Generate self to writer

Provided Methods§

Source

fn bits<C: Counter>(&self) -> Result<C, Self::Error>
where Self: Sized,

Returns length of self in bits, if possible

Source

fn bits_len<C: Counter, E: Endianness>(&self) -> Result<C, Self::Error>
where Self: Sized,

👎Deprecated since 4.0.0:

use of bits() is preferred

Returns total length of self, if possible

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§