aboutsummaryrefslogtreecommitdiff
path: root/vendor/weezl/tests/roundtrip.rs
blob: f124fae54ef81e0dd67b10aae760f68190f73aa1 (plain) (blame)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::{env, fs};
use weezl::{decode, encode, BitOrder};

#[derive(Clone, Copy, Debug)]
enum Flavor {
    Gif,
    Tiff,
}

#[test]
fn roundtrip_all() {
    let file = env::args().next().unwrap();
    let data = fs::read(file).unwrap();

    for &flavor in &[Flavor::Gif, Flavor::Tiff] {
        for &bit_order in &[BitOrder::Lsb, BitOrder::Msb] {
            for bit_width in 2..8 {
                let data: Vec<_> = data
                    .iter()
                    .copied()
                    .map(|b| b & ((1 << bit_width) - 1))
                    .collect();

                println!("Roundtrip test {:?} {:?} {}", flavor, bit_order, bit_width);
                assert_roundtrips(&*data, flavor, bit_width, bit_order);
            }
        }
    }
}

fn assert_roundtrips(data: &[u8], flavor: Flavor, bit_width: u8, bit_order: BitOrder) {
    let (c, d): (
        fn(BitOrder, u8) -> encode::Encoder,
        fn(BitOrder, u8) -> decode::Decoder,
    ) = match flavor {
        Flavor::Gif => (encode::Encoder::new, decode::Decoder::new),
        Flavor::Tiff => (
            encode::Encoder::with_tiff_size_switch,
            decode::Decoder::with_tiff_size_switch,
        ),
    };
    let mut encoder = c(bit_order, bit_width);
    let mut buffer = Vec::with_capacity(2 * data.len() + 40);
    let _ = encoder.into_stream(&mut buffer).encode_all(data);

    let mut decoder = d(bit_order, bit_width);
    let mut compare = vec![];
    let result = decoder
        .into_stream(&mut compare)
        .decode_all(buffer.as_slice());
    assert!(
        result.status.is_ok(),
        "{:?}, {}, {:?}",
        bit_order,
        bit_width,
        result.status
    );
    assert!(
        data == &*compare,
        "{:?}, {}\n{:?}\n{:?}",
        bit_order,
        bit_width,
        data,
        compare
    );
}