| 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 |
fn expect(&mut self, bits: Bits) -> Result<(), Option<Bits>> { |
| 50 |
match self.peek(bits.len) { |
| 51 |
None => Err(None), |
| 52 |
Some(val) if val == bits.data => Ok(()), |
| 53 |
Some(val) => Err(Some(Bits { data: val, len: bits.len })) |
| 54 |
} |
| 55 |
} |
| 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 |
fn write(&mut self, bits: Bits) -> Result<(), Self::Error> { |
| 75 |
self.partial |= (bits.data as u32) << (32 - self.len - bits.len); |
| 76 |
self.len += bits.len; |
| 77 |
while self.len >= 8 { |
| 78 |
self.data.push((self.partial >> 24) as u8); |
| 79 |
self.partial <<= 8; |
| 80 |
self.len -= 8; |
| 81 |
} |
| 82 |
Ok(()) |
| 83 |
} |
| 84 |
} |
| 85 |
impl VecWriter { |
| 86 |
pub fn new() -> Self { |
| 87 |
VecWriter { |
| 88 |
data: Vec::new(), |
| 89 |
partial: 0, |
| 90 |
len: 0 |
| 91 |
} |
| 92 |
} |
| 93 |
// with capacity of `n` bits. |
| 94 |
pub fn with_capacity(n: usize) -> Self { |
| 95 |
VecWriter { |
| 96 |
data: Vec::with_capacity((n + 7) / 8), |
| 97 |
partial: 0, |
| 98 |
len: 0 |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
/// Pad the output with `0` bits until it is at a byte boundary. |
| 103 |
pub fn pad(&mut self) { |
| 104 |
if self.len > 0 { |
| 105 |
self.data.push((self.partial >> 24) as u8); |
| 106 |
self.partial = 0; |
| 107 |
self.len = 0; |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
/// pad and return the accumulated bytes |
| 112 |
pub fn finish(mut self) -> Vec<u8> { |
| 113 |
self.pad(); |
| 114 |
self.data |
| 115 |
} |
| 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 |
pub fn new(read: R) -> Result<Self, E> { |
| 126 |
let mut bits = ByteReader { |
| 127 |
read, |
| 128 |
partial: 0, |
| 129 |
valid: 0 |
| 130 |
}; |
| 131 |
bits.fill()?; |
| 132 |
Ok(bits) |
| 133 |
} |
| 134 |
fn fill(&mut self) -> Result<(), E> { |
| 135 |
while self.valid < 16 { |
| 136 |
match self.read.next() { |
| 137 |
Some(Ok(byte)) => { |
| 138 |
self.partial = self.partial << 8 | byte as u32; |
| 139 |
self.valid += 8; |
| 140 |
} |
| 141 |
Some(Err(e)) => return Err(e), |
| 142 |
None => break |
| 143 |
} |
| 144 |
} |
| 145 |
Ok(()) |
| 146 |
} |
| 147 |
/// Print the remaining data |
| 148 |
/// |
| 149 |
/// Note: For debug purposes only, not part of the API. |
| 150 |
pub fn print_remaining(&mut self) { |
| 151 |
println!("partial: {:0w$b}, valid: {}", self.partial & ((1 << self.valid) - 1), self.valid, w=self.valid as usize); |
| 152 |
while let Some(Ok(b)) = self.read.next() { |
| 153 |
print!("{:08b} ", b); |
| 154 |
} |
| 155 |
println!(); |
| 156 |
} |
| 157 |
pub fn print_peek(&self) { |
| 158 |
println!("partial: {:0w$b}, valid: {}", self.partial & ((1 << self.valid) - 1), self.valid, w=self.valid as usize); |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
pub fn slice_reader(slice: &[u8]) -> ByteReader<impl Iterator<Item=Result<u8, Infallible>> + '_> { |
| 163 |
ByteReader::new(slice.iter().cloned().map(Ok)).unwrap() |
| 164 |
} |
| 165 |
pub fn slice_bits(slice: &[u8]) -> impl Iterator<Item=bool> + '_ { |
| 166 |
slice.iter().flat_map(|&b| [7,6,5,4,3,2,1,0].map(|i| (b >> i) & 1 != 0)) |
| 167 |
} |
| 168 |
|
| 169 |
impl<E, R: Iterator<Item=Result<u8, E>>> BitReader for ByteReader<R> { |
| 170 |
type Error = E; |
| 171 |
|
| 172 |
fn peek(&self, bits: u8) -> Option<u16> { |
| 173 |
assert!(bits <= 16); |
| 174 |
if self.valid >= bits { |
| 175 |
let shift = self.valid - bits; |
| 176 |
let out = (self.partial >> shift) as u16 & ((1 << bits) - 1); |
| 177 |
Some(out) |
| 178 |
} else { |
| 179 |
None |
| 180 |
} |
| 181 |
} |
| 182 |
fn consume(&mut self, bits: u8) -> Result<(), E> { |
| 183 |
self.valid -= bits; |
| 184 |
self.fill() |
| 185 |
} |
| 186 |
fn bits_to_byte_boundary(&self) -> u8 { |
| 187 |
self.valid & 7 |
| 188 |
} |
| 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 |
fn not(self) -> Self { |
| 207 |
match self { |
| 208 |
Color::Black => Color::White, |
| 209 |
Color::White => Color::Black, |
| 210 |
} |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
struct Transitions<'a> { |
| 215 |
edges: &'a [u16], |
| 216 |
pos: usize |
| 217 |
} |
| 218 |
impl<'a> Transitions<'a> { |
| 219 |
fn new(edges: &'a [u16]) -> Self { |
| 220 |
Transitions { edges, pos: 0 } |
| 221 |
} |
| 222 |
fn seek_back(&mut self, start: u16) { |
| 223 |
self.pos = self.pos.min(self.edges.len().saturating_sub(1)); |
| 224 |
while self.pos > 0 { |
| 225 |
if start < self.edges[self.pos-1] { |
| 226 |
self.pos -= 1; |
| 227 |
} else { |
| 228 |
break; |
| 229 |
} |
| 230 |
} |
| 231 |
} |
| 232 |
fn next_color(&mut self, start: u16, color: Color, start_of_row: bool) -> Option<u16> { |
| 233 |
if start_of_row { |
| 234 |
if color == Color::Black { |
| 235 |
self.pos = 1; |
| 236 |
return self.edges.get(0).cloned() |
| 237 |
} else { |
| 238 |
self.pos = 2; |
| 239 |
return self.edges.get(1).cloned() |
| 240 |
} |
| 241 |
} |
| 242 |
while self.pos < self.edges.len() { |
| 243 |
if self.edges[self.pos] <= start { |
| 244 |
self.pos += 1; |
| 245 |
continue; |
| 246 |
} |
| 247 |
|
| 248 |
if (self.pos % 2 == 0) != (color == Color::Black) { |
| 249 |
self.pos += 1; |
| 250 |
} |
| 251 |
|
| 252 |
break; |
| 253 |
} |
| 254 |
if self.pos < self.edges.len() { |
| 255 |
let val = self.edges[self.pos]; |
| 256 |
self.pos += 1; |
| 257 |
Some(val) |
| 258 |
} else { |
| 259 |
None |
| 260 |
} |
| 261 |
} |
| 262 |
fn next(&mut self) -> Option<u16> { |
| 263 |
if self.pos < self.edges.len() { |
| 264 |
let val = self.edges[self.pos]; |
| 265 |
self.pos += 1; |
| 266 |
Some(val) |
| 267 |
} else { |
| 268 |
None |
| 269 |
} |
| 270 |
} |
| 271 |
fn peek(&self) -> Option<u16> { |
| 272 |
self.edges.get(self.pos).cloned() |
| 273 |
} |
| 274 |
fn skip(&mut self, n: usize) { |
| 275 |
self.pos += n; |
| 276 |
} |
| 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 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 287 |
write!(f, "d={:0b} w={}", self.data, self.len) |
| 288 |
} |
| 289 |
} |
| 290 |
impl fmt::Display for Bits { |
| 291 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 292 |
write!(f, "{:0w$b}", self.data & ((1 << self.len) - 1), w=self.len as usize) |
| 293 |
} |
| 294 |
} |