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
use std::io;
pub trait DataSource {
type Item: Copy + PartialEq;
#[inline]
fn read(&mut self, &mut [Self::Item]) -> io::Result<usize>;
}
#[derive(Debug)]
pub struct ReadDataSource<R: io::Read>(R);
impl<R: io::Read> ReadDataSource<R> {
#[inline]
pub fn new(inner: R) -> Self {
ReadDataSource(inner)
}
#[inline]
pub fn into_inner(self) -> R {
self.0
}
}
impl<R: io::Read> DataSource for ReadDataSource<R> {
type Item = u8;
#[inline]
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
self.0.read(buffer)
}
}
#[derive(Debug)]
pub struct RWDataSource<RW: io::Read + io::Write>(RW);
impl<RW: io::Read + io::Write> RWDataSource<RW> {
pub fn new(inner: RW) -> Self {
RWDataSource(inner)
}
#[inline]
pub fn into_inner(self) -> RW {
self.0
}
}
impl<RW: io::Read + io::Write> DataSource for RWDataSource<RW> {
type Item = u8;
#[inline]
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
self.0.read(buffer)
}
}
impl<RW: io::Read + io::Write> io::Write for RWDataSource<RW> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
#[derive(Debug)]
pub struct IteratorDataSource<I: Iterator>(I);
impl<I: Iterator> IteratorDataSource<I> {
#[inline]
pub fn new(inner: I) -> Self {
IteratorDataSource(inner)
}
#[inline]
pub fn into_inner(self) -> I {
self.0
}
}
impl<I: Iterator> DataSource for IteratorDataSource<I>
where I::Item: Copy + PartialEq {
type Item = I::Item;
#[inline]
fn read(&mut self, buffer: &mut [I::Item]) -> io::Result<usize> {
let mut n = 0;
while buffer.len() > n {
if let Some(i) = self.0.next() {
buffer[n] = i;
} else {
break;
}
n += 1;
}
Ok(n)
}
}