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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use crate::byte_writer::ByteWriter;
use crate::error::{InError, OutError};
use crate::util;
use crate::util::literals::*;
use std::io::{Bytes, Read, Write};
pub struct Reader<R: Read> {
in_bytes: Bytes<R>,
}
impl<R: Read> Reader<R> {
pub fn new(read: R) -> Self {
Reader {
in_bytes: read.bytes(),
}
}
}
impl<R: Read> Iterator for Reader<R> {
type Item = Result<u8, InError>;
fn next(&mut self) -> Option<Self::Item> {
let mut value = 0u8;
let mut i = 7i8;
while i >= 0 {
let in_byte = self.in_bytes.next();
match in_byte {
None => {
return if i == 7 {
None
} else {
Some(Err(InError::ShortIO {
bytes: 7 - i as usize,
expected: 8,
}))
}
}
Some(in_byte) => match in_byte {
Ok(in_byte) => {
let in_byte = in_byte as char;
match in_byte {
'0' => {}
'1' => {
value |= 1 << i;
}
_ => {
if in_byte.is_ascii_whitespace() {
continue;
} else {
return Some(Err(InError::InvalidByte(in_byte)));
}
}
}
}
Err(e) => {
return Some(Err(InError::StdIO(e)));
}
},
}
i -= 1;
}
Some(Ok(value))
}
}
pub struct Writer<W: Write> {
out_bytes: W,
}
impl<W: Write> Writer<W> {
pub fn new(out_bytes: W) -> Self {
Writer { out_bytes }
}
}
impl<W: Write> ByteWriter for Writer<W> {
fn write(&mut self, byte: u8) -> Result<(), OutError> {
let mut bit_string = [_0; 8];
for i in (0..8).rev() {
if (byte & (1 << i)) != 0 {
bit_string[7 - i] = _1;
}
}
util::write(&mut self.out_bytes, bit_string.as_slice(), 8)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn read() {
let input = [
_0, _1, _0, _0, _1, _0, _1, _0, _0, _1, _0, _1, _1, _1, _1, _1,
];
let mut reader = Reader::new(input.as_slice());
assert_eq!(0b01001010u8, reader.next().unwrap().unwrap());
assert_eq!(0b01011111u8, reader.next().unwrap().unwrap());
assert!(reader.next().is_none());
}
#[test]
fn write() {
let input = 0b10110100u8;
let expected = [_1, _0, _1, _1, _0, _1, _0, _0];
let mut output = [0u8; 8];
let mut writer = Writer::new(output.as_mut_slice());
writer.write(input).unwrap();
assert_eq!(expected, output);
}
}
#[cfg(all(test, feature = "benchmark"))]
mod benchs {
extern crate test;
use super::*;
#[bench]
fn read(b: &mut test::Bencher) {
const N: usize = 1024 * 1024;
static INPUT: [u8; N] = [_1; N];
b.iter(|| {
let reader = Reader::new(INPUT.as_slice());
let _ = reader.collect::<Vec<Result<u8, InError>>>();
});
}
#[bench]
fn write(b: &mut test::Bencher) {
const N: usize = 1024 * 1024;
static mut OUTPUT: [u8; N] = [_0; N];
b.iter(|| unsafe {
let mut writer = Writer::new(OUTPUT.as_mut_slice());
for _ in 0..N / 8 {
writer.write(255u8).unwrap();
}
});
}
}