simple_arithmetic_coding/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#![forbid(unsafe_code)]

use std::io::{BufRead, Write};

use io::{Next, Push};

mod codec;
mod fenwick;
mod io;
mod bitvec;

const SIZE: usize = 257;
const EOF: usize = 256;

pub fn encode_routine<I,O> (input_handle: &mut I, output_handle: &mut O) -> Result<(), std::io::Error>
where I: BufRead, O: Write
{
    let mut encoder = codec::ArithmeticEncoder::new(SIZE);
    let mut bits_out = io::Output::new(output_handle, 8000);
    let mut bits_in = io::Input::new(input_handle)?;

    while let Some(byte) = bits_in.next_byte()? {
        encoder.encode(byte as usize, &mut bits_out)?;
        encoder.discover(byte as usize);
    }
    encoder.encode(EOF, &mut bits_out)?;
    encoder.finish(&mut bits_out)?;
    bits_out.flush()?;

    Ok(())
}

pub fn decode_routine<I,O> (input_handle: &mut I, output_handle: &mut O) -> Result<(), std::io::Error>
where I: BufRead, O: Write
{
    let mut decoder = codec::ArithmeticDecoder::new(SIZE);
    let mut bits_out = io::Output::new(output_handle, 8000);
    let mut bits_in = io::Input::new(input_handle)?;

    decoder.begin(&mut bits_in)?;
    loop {
        let s = decoder.decode(&mut bits_in)?;
        if s == EOF {
            break;
        }
        bits_out.push_byte(s as u8)?;
        decoder.discover(s);
    }
    bits_out.flush()?;
    Ok(())
}