cat_reader/
lib.rs

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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! Adapter for reading through multiple files continuously.
#![forbid(missing_docs)]
#![cfg_attr(test, deny(warnings))]

use std::fmt;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::path::Path;

/// This makes testing easier.
trait FileLike: fmt::Debug + Read + Sized {
    fn open<P: AsRef<Path>>(p: P) -> io::Result<Self>;
}
impl FileLike for File {
    #[inline]
    fn open<P: AsRef<Path>>(p: P) -> io::Result<Self> {
        File::open(p)
    }
}

/// Generalised version, for easier testing.
struct InnerReader<R, I: IntoIterator> {
    curr: Option<R>,
    rest: I::IntoIter,
}
impl<R, I> InnerReader<R, I>
where
    R: FileLike,
    I: IntoIterator,
    I::Item: AsRef<Path>,
{
    #[inline]
    fn new(iter: I) -> InnerReader<R, I> {
        InnerReader {
            curr: None,
            rest: iter.into_iter(),
        }
    }
}
impl<I> InnerReader<File, I>
where
    I: IntoIterator,
    I::Item: AsRef<Path>,
    I::IntoIter: Clone,
{
    #[inline]
    fn try_clone(&self) -> io::Result<InnerReader<File, I>> {
        Ok(InnerReader {
            curr: match self.curr.as_ref().map(|f| f.try_clone()) {
                Some(Err(e)) => return Err(e),
                Some(Ok(f)) => Some(f),
                None => None,
            },
            rest: self.rest.clone(),
        })
    }
}
impl<R, I> Read for InnerReader<R, I>
where
    R: FileLike,
    I: IntoIterator,
    I::Item: AsRef<Path>,
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }

        loop {
            if self.curr.is_none() {
                self.curr = match self.rest.next() {
                    None => return Ok(0),
                    Some(p) => Some(try!(FileLike::open(p))),
                };
            }

            let n = self.curr.as_mut().unwrap().read(buf);
            match n {
                Ok(0) => self.curr = None,
                val => return val,
            }
        }
    }
}
impl<R, I> fmt::Debug for InnerReader<R, I>
where
    R: fmt::Debug,
    I: IntoIterator,
    I::Item: fmt::Debug,
    I::IntoIter: Clone,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let rest: Vec<_> = self.rest.clone().collect();
        f.debug_struct("CatReader")
            .field("curr", &self.curr)
            .field("rest", &rest)
            .finish()
    }
}

/// Adapter for reading through multiple files continuously.
pub struct CatReader<I: IntoIterator> {
    inner: InnerReader<File, I>,
}
impl<I> CatReader<I>
where
    I: IntoIterator,
    I::Item: AsRef<Path>,
{
    /// Creates a new `CatReader` from an iterator of file names.
    #[inline]
    pub fn new(iter: I) -> CatReader<I> {
        CatReader {
            inner: InnerReader::new(iter),
        }
    }

    /// Convenience method for creating a `BufReader` of a `CatReader`.
    #[inline]
    pub fn buffered(iter: I) -> BufReader<CatReader<I>> {
        BufReader::new(CatReader::new(iter))
    }
}
impl<I> CatReader<I>
where
    I: IntoIterator,
    I::Item: AsRef<Path>,
    I::IntoIter: Clone,
{
    /// Tries to clone the reader.
    #[inline]
    pub fn try_clone(&self) -> io::Result<CatReader<I>> {
        Ok(CatReader {
            inner: self.inner.try_clone()?,
        })
    }
}
impl<I> Read for CatReader<I>
where
    I: IntoIterator,
    I::Item: AsRef<Path>,
{
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }
}
impl<I> fmt::Debug for CatReader<I>
where
    I: IntoIterator,
    I::Item: fmt::Debug,
    I::IntoIter: Clone,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.inner, f)
    }
}

#[cfg(test)]
mod tests {
    use super::{FileLike, InnerReader};
    use std::io::{self, Read};
    use std::path::Path;

    impl FileLike for &'static [u8] {
        fn open<P: AsRef<Path>>(p: P) -> io::Result<&'static [u8]> {
            let string = p.as_ref().to_string_lossy().into_owned();
            let reference: &str = &string;
            match reference {
                "test1.txt" => Ok(b"some\ntext\n"),
                "dir/other.test.txt" => Ok(b"here's "),
                _ => Err(io::Error::new(io::ErrorKind::NotFound, "file missing")),
            }
        }
    }

    #[test]
    fn everything() {
        let strs = &["dir/other.test.txt", "404", "test1.txt"];

        let mut reader: InnerReader<&'static [u8], _> = InnerReader::new(strs);
        assert_eq!(
            format!("{:?}", reader),
            "CatReader { curr: None, rest: [\"dir/other.test.txt\", \"404\", \
             \"test1.txt\"] }"
        );

        let mut buf = [];
        assert_eq!(reader.read(&mut buf).unwrap(), 0);
        assert_eq!(
            format!("{:?}", reader),
            "CatReader { curr: None, rest: [\"dir/other.test.txt\", \"404\", \
             \"test1.txt\"] }"
        );

        let mut buf = [0];
        assert_eq!(reader.read(&mut buf).unwrap(), 1);
        assert_eq!(buf, [104]);
        assert_eq!(
            format!("{:?}", reader),
            "CatReader { curr: Some([101, 114, 101, 39, 115, 32]), rest: [\"404\", \
             \"test1.txt\"] }"
        );

        let mut buf = Vec::new();
        assert!(reader.read_to_end(&mut buf).is_err());
        assert_eq!(reader.read_to_end(&mut buf).unwrap(), 10);
        assert_eq!(buf, b"ere's some\ntext\n");
        assert_eq!(
            format!("{:?}", reader),
            "CatReader { curr: None, rest: [] }"
        );
    }
}