Coverage Report

Created: 2025-11-24 07:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/fax-0.2.6/src/lib.rs
Line
Count
Source
1
use std::convert::Infallible;
2
use std::io::{self, Read};
3
use std::iter::Map;
4
use std::ops::Not;
5
use std::fmt;
6
7
#[cfg(feature="debug")]
8
macro_rules! debug {
9
    ($($arg:expr),*) => (
10
        println!($($arg),*)
11
    )
12
}
13
#[cfg(not(feature="debug"))]
14
macro_rules! debug {
15
    ($($arg:expr),*) => (
16
        ()
17
    )
18
}
19
20
pub mod maps;
21
22
/// Decoder module
23
pub mod decoder;
24
25
/// Encoder module
26
pub mod encoder;
27
28
/// TIFF helper functions
29
pub mod tiff;
30
31
/// Trait used to read data bitwise.
32
/// 
33
/// For lazy people `ByteReader` is provided which implements this trait.
34
pub trait BitReader {
35
    type Error;
36
37
    /// look at the next (up to 16) bits of data
38
    /// 
39
    /// Data is returned in the lower bits of the `u16`.
40
    fn peek(&self, bits: u8) -> Option<u16>;
41
42
    /// Consume the given amount of bits from the input.
43
    fn consume(&mut self, bits: u8) -> Result<(), Self::Error>;
44
45
    /// Assert that the next bits matches the given pattern.
46
    /// 
47
    /// If it does not match, the found pattern is returned if enough bits are aviable.
48
    /// Otherwise None is returned.
49
0
    fn expect(&mut self, bits: Bits) -> Result<(), Option<Bits>> {
50
0
        match self.peek(bits.len) {
51
0
            None => Err(None),
52
0
            Some(val) if val == bits.data => Ok(()),
53
0
            Some(val) => Err(Some(Bits { data: val, len: bits.len }))
54
        }
55
0
    }
56
57
    fn bits_to_byte_boundary(&self) -> u8;
58
}
59
60
/// Trait to write data bitwise
61
/// 
62
/// The `VecWriter` struct is provided for convinience.
63
pub trait BitWriter {
64
    type Error;
65
    fn write(&mut self, bits: Bits) -> Result<(), Self::Error>;
66
}
67
pub struct VecWriter {
68
    data: Vec<u8>,
69
    partial: u32,
70
    len: u8
71
}
72
impl BitWriter for VecWriter {
73
    type Error = Infallible;
74
0
    fn write(&mut self, bits: Bits) -> Result<(), Self::Error> {
75
0
        self.partial |= (bits.data as u32) << (32 - self.len - bits.len);
76
0
        self.len += bits.len;
77
0
        while self.len >= 8 {
78
0
            self.data.push((self.partial >> 24) as u8);
79
0
            self.partial <<= 8;
80
0
            self.len -= 8;
81
0
        }
82
0
        Ok(())
83
0
    }
84
}
85
impl VecWriter {
86
0
    pub fn new() -> Self {
87
0
        VecWriter {
88
0
            data: Vec::new(),
89
0
            partial: 0,
90
0
            len: 0
91
0
        }
92
0
    }
93
    // with capacity of `n` bits.
94
0
    pub fn with_capacity(n: usize) -> Self {
95
0
        VecWriter {
96
0
            data: Vec::with_capacity((n + 7) / 8),
97
0
            partial: 0,
98
0
            len: 0
99
0
        }
100
0
    }
101
102
    /// Pad the output with `0` bits until it is at a byte boundary.
103
0
    pub fn pad(&mut self) {
104
0
        if self.len > 0 {
105
0
            self.data.push((self.partial >> 24) as u8);
106
0
            self.partial = 0;
107
0
            self.len = 0;
108
0
        }
109
0
    }
110
111
    /// pad and return the accumulated bytes
112
0
    pub fn finish(mut self) -> Vec<u8> {
113
0
        self.pad();
114
0
        self.data
115
0
    }
116
}
117
118
pub struct ByteReader<R> {
119
    read: R,
120
    partial: u32,
121
    valid: u8,
122
}
123
impl<E, R: Iterator<Item=Result<u8, E>>> ByteReader<R> {
124
    /// Construct a new `ByteReader` from an iterator of `u8`
125
305
    pub fn new(read: R) -> Result<Self, E> {
126
305
        let mut bits = ByteReader {
127
305
            read,
128
305
            partial: 0,
129
305
            valid: 0
130
305
        };
131
305
        bits.fill()?;
132
305
        Ok(bits)
133
305
    }
<fax::ByteReader<std::io::Bytes<std::io::buffered::bufreader::BufReader<std::io::Take<&mut std::io::cursor::Cursor<&[u8]>>>>>>::new
Line
Count
Source
125
305
    pub fn new(read: R) -> Result<Self, E> {
126
305
        let mut bits = ByteReader {
127
305
            read,
128
305
            partial: 0,
129
305
            valid: 0
130
305
        };
131
305
        bits.fill()?;
132
305
        Ok(bits)
133
305
    }
Unexecuted instantiation: <fax::ByteReader<core::iter::adapters::map::Map<core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<u8>>, core::result::Result<u8, core::convert::Infallible>::Ok>>>::new
134
4.25M
    fn fill(&mut self) -> Result<(), E> {
135
5.55M
        while self.valid < 16 {
136
1.29M
            match self.read.next() {
137
1.29M
                Some(Ok(byte)) => {
138
1.29M
                    self.partial = self.partial << 8 | byte as u32;
139
1.29M
                    self.valid += 8;
140
1.29M
                }
141
0
                Some(Err(e)) => return Err(e),
142
743
                None => break
143
            }
144
        }
145
4.25M
        Ok(())
146
4.25M
    }
<fax::ByteReader<std::io::Bytes<std::io::buffered::bufreader::BufReader<std::io::Take<&mut std::io::cursor::Cursor<&[u8]>>>>>>::fill
Line
Count
Source
134
4.25M
    fn fill(&mut self) -> Result<(), E> {
135
5.55M
        while self.valid < 16 {
136
1.29M
            match self.read.next() {
137
1.29M
                Some(Ok(byte)) => {
138
1.29M
                    self.partial = self.partial << 8 | byte as u32;
139
1.29M
                    self.valid += 8;
140
1.29M
                }
141
0
                Some(Err(e)) => return Err(e),
142
743
                None => break
143
            }
144
        }
145
4.25M
        Ok(())
146
4.25M
    }
Unexecuted instantiation: <fax::ByteReader<core::iter::adapters::map::Map<core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<u8>>, core::result::Result<u8, core::convert::Infallible>::Ok>>>::fill
147
    /// Print the remaining data
148
    /// 
149
    /// Note: For debug purposes only, not part of the API.
150
0
    pub fn print_remaining(&mut self) {
151
0
        println!("partial: {:0w$b}, valid: {}", self.partial & ((1 << self.valid) - 1), self.valid, w=self.valid as usize);
152
0
        while let Some(Ok(b)) = self.read.next() {
153
0
            print!("{:08b} ", b);
154
0
        }
155
0
        println!();
156
0
    }
157
0
    pub fn print_peek(&self) {
158
0
        println!("partial: {:0w$b}, valid: {}", self.partial & ((1 << self.valid) - 1), self.valid, w=self.valid as usize);
159
0
    }
160
}
161
162
0
pub fn slice_reader(slice: &[u8]) -> ByteReader<impl Iterator<Item=Result<u8, Infallible>> + '_> {
163
0
    ByteReader::new(slice.iter().cloned().map(Ok)).unwrap()
164
0
}
165
0
pub fn slice_bits(slice: &[u8]) -> impl Iterator<Item=bool> + '_ {
166
0
    slice.iter().flat_map(|&b| [7,6,5,4,3,2,1,0].map(|i| (b >> i) & 1 != 0))
167
0
}
168
169
impl<E, R: Iterator<Item=Result<u8, E>>> BitReader for ByteReader<R> {
170
    type Error = E;
171
172
4.25M
    fn peek(&self, bits: u8) -> Option<u16> {
173
4.25M
        assert!(bits <= 16);
174
4.25M
        if self.valid >= bits {
175
4.25M
            let shift = self.valid - bits;
176
4.25M
            let out = (self.partial >> shift) as u16 & ((1 << bits) - 1);
177
4.25M
            Some(out)
178
        } else {
179
122
            None
180
        }
181
4.25M
    }
<fax::ByteReader<std::io::Bytes<std::io::buffered::bufreader::BufReader<std::io::Take<&mut std::io::cursor::Cursor<&[u8]>>>>> as fax::BitReader>::peek
Line
Count
Source
172
4.25M
    fn peek(&self, bits: u8) -> Option<u16> {
173
4.25M
        assert!(bits <= 16);
174
4.25M
        if self.valid >= bits {
175
4.25M
            let shift = self.valid - bits;
176
4.25M
            let out = (self.partial >> shift) as u16 & ((1 << bits) - 1);
177
4.25M
            Some(out)
178
        } else {
179
122
            None
180
        }
181
4.25M
    }
Unexecuted instantiation: <fax::ByteReader<_> as fax::BitReader>::peek
182
4.25M
    fn consume(&mut self, bits: u8) -> Result<(), E> {
183
4.25M
        self.valid -= bits;
184
4.25M
        self.fill()
185
4.25M
    }
<fax::ByteReader<std::io::Bytes<std::io::buffered::bufreader::BufReader<std::io::Take<&mut std::io::cursor::Cursor<&[u8]>>>>> as fax::BitReader>::consume
Line
Count
Source
182
4.25M
    fn consume(&mut self, bits: u8) -> Result<(), E> {
183
4.25M
        self.valid -= bits;
184
4.25M
        self.fill()
185
4.25M
    }
Unexecuted instantiation: <fax::ByteReader<_> as fax::BitReader>::consume
186
0
    fn bits_to_byte_boundary(&self) -> u8 {
187
0
        self.valid & 7
188
0
    }
189
}
190
191
192
#[test]
193
fn test_bits() {
194
    let mut bits = slice_reader(&[0b0000_1101, 0b1010_0000]);
195
    assert_eq!(maps::black::decode(&mut bits), Some(42));
196
}
197
198
/// Enum used to signal black/white.
199
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
200
pub enum Color {
201
    Black,
202
    White
203
}
204
impl Not for Color {
205
    type Output = Self;
206
7.30M
    fn not(self) -> Self {
207
7.30M
        match self {
208
3.17M
            Color::Black => Color::White,
209
4.13M
            Color::White => Color::Black,
210
        }
211
7.30M
    }
212
}
213
214
struct Transitions<'a> {
215
    edges: &'a [u16],
216
    pos: usize
217
}
218
impl<'a> Transitions<'a> {
219
595k
    fn new(edges: &'a [u16]) -> Self {
220
595k
        Transitions { edges, pos: 0 }
221
595k
    }
222
380k
    fn seek_back(&mut self, start: u16) {
223
380k
        self.pos = self.pos.min(self.edges.len().saturating_sub(1));
224
704k
        while self.pos > 0 {
225
598k
            if start < self.edges[self.pos-1] {
226
324k
                self.pos -= 1;
227
324k
            } else {
228
273k
                break;
229
            }
230
        }
231
380k
    }
232
2.00M
    fn next_color(&mut self, start: u16, color: Color, start_of_row: bool) -> Option<u16> {
233
2.00M
        if start_of_row {
234
489k
            if color == Color::Black {
235
489k
                self.pos = 1;
236
489k
                return self.edges.get(0).cloned()
237
            } else {
238
0
                self.pos = 2;
239
0
                return self.edges.get(1).cloned()
240
            }
241
1.51M
        }
242
2.35M
        while self.pos < self.edges.len() {
243
2.21M
            if self.edges[self.pos] <= start {
244
831k
                self.pos += 1;
245
831k
                continue;
246
1.38M
            }
247
248
1.38M
            if (self.pos % 2 == 0) != (color == Color::Black) {
249
399k
                self.pos += 1;
250
985k
            }
251
252
1.38M
            break;
253
        }
254
1.51M
        if self.pos < self.edges.len() {
255
1.32M
            let val = self.edges[self.pos];
256
1.32M
            self.pos += 1;
257
1.32M
            Some(val)
258
        } else {
259
194k
            None
260
        }
261
2.00M
    }
262
2.65k
    fn next(&mut self) -> Option<u16> {
263
2.65k
        if self.pos < self.edges.len() {
264
1.24k
            let val = self.edges[self.pos];
265
1.24k
            self.pos += 1;
266
1.24k
            Some(val)
267
        } else {
268
1.41k
            None
269
        }
270
2.65k
    }
271
0
    fn peek(&self) -> Option<u16> {
272
0
        self.edges.get(self.pos).cloned()
273
0
    }
274
0
    fn skip(&mut self, n: usize) {
275
0
        self.pos += n;
276
0
    }
277
}
278
279
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
280
pub struct Bits {
281
    pub data: u16,
282
    pub len: u8
283
}
284
285
impl fmt::Debug for Bits {
286
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287
0
        write!(f, "d={:0b} w={}", self.data, self.len)
288
0
    }
289
}
290
impl fmt::Display for Bits {
291
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292
0
        write!(f, "{:0w$b}", self.data & ((1 << self.len) - 1), w=self.len as usize)
293
0
    }
294
}