Module bitstream_io::write[][src]

Expand description

Traits and implementations for writing bits to a stream.

Example

Writing the initial STREAMINFO block to a FLAC file, as documented in its specification.

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

let mut flac: Vec<u8> = Vec::new();
{
    let mut writer = BitWriter::endian(&mut flac, BigEndian);

    // stream marker
    writer.write_bytes(b"fLaC").unwrap();

    // metadata block header
    let last_block: bool = false;
    let block_type: u8 = 0;
    let block_size: u32 = 34;
    writer.write_bit(last_block).unwrap();
    writer.write(7, block_type).unwrap();
    writer.write(24, block_size).unwrap();

    // STREAMINFO block
    let minimum_block_size: u16 = 4096;
    let maximum_block_size: u16 = 4096;
    let minimum_frame_size: u32 = 1542;
    let maximum_frame_size: u32 = 8546;
    let sample_rate: u32 = 44100;
    let channels: u8 = 2;
    let bits_per_sample: u8 = 16;
    let total_samples: u64 = 304844;
    writer.write(16, minimum_block_size).unwrap();
    writer.write(16, maximum_block_size).unwrap();
    writer.write(24, minimum_frame_size).unwrap();
    writer.write(24, maximum_frame_size).unwrap();
    writer.write(20, sample_rate).unwrap();
    writer.write(3, channels - 1).unwrap();
    writer.write(5, bits_per_sample - 1).unwrap();
    writer.write(36, total_samples).unwrap();
}

// STREAMINFO's MD5 sum

// Note that the wrapped writer can be used once bitstream writing
// is finished at exactly the position one would expect.

flac.write_all(
    b"\xFA\xF2\x69\x2F\xFD\xEC\x2D\x5B\x30\x01\x76\xB4\x62\x88\x7D\x92")
    .unwrap();

assert_eq!(flac, vec![0x66,0x4C,0x61,0x43,0x00,0x00,0x00,0x22,
                      0x10,0x00,0x10,0x00,0x00,0x06,0x06,0x00,
                      0x21,0x62,0x0A,0xC4,0x42,0xF0,0x00,0x04,
                      0xA6,0xCC,0xFA,0xF2,0x69,0x2F,0xFD,0xEC,
                      0x2D,0x5B,0x30,0x01,0x76,0xB4,0x62,0x88,
                      0x7D,0x92]);

Structs

BitCounter

For counting the number of bits written but generating no output.

BitRecorder

For recording writes in order to play them back on another writer

BitWriter

For writing bit values to an underlying stream in a given endianness.

ByteWriter

For writing aligned bytes to a stream of bytes in a given endianness.

SignedValue

A generic signed value for stream recording purposes

UnsignedValue

A generic unsigned value for stream recording purposes

Traits

BitWrite

A trait for anything that can write a variable number of potentially un-aligned values to an output stream

ByteWrite

A trait for anything that can write aligned values to an output stream

HuffmanWrite

A trait for anything that can write Huffman codes of a given endianness to an output stream