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
// License: see LICENSE file at root directory of `master` branch

//! # Root

use std::{
    fs::{self, File, ReadDir},
    io::{self, BufRead, BufReader, Error, ErrorKind, Read},
    path::{Path, PathBuf},
};

use crate::filter;

/// # File discovery
///
/// ## Notes
///
/// - You can make this struct by [`::find_files()`][::find_files()].
/// - If sub directories are symlinks, they will be ignored.
///
/// [::find_files()]: fn.find_files.html
#[derive(Debug)]
pub struct FileDiscovery<F> where F: filter::Filter {

    /// # Filter
    filter: F,

    /// # Recursive
    recursive: bool,

    /// # Current
    current: ReadDir,

    /// # Sub directories
    sub_dirs: Option<Vec<PathBuf>>,

}

impl<F> Iterator for FileDiscovery<F> where F: filter::Filter {

    type Item = io::Result<PathBuf>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.current.next() {
                Some(entry) => match entry {
                    Ok(entry) => match entry.file_type() {
                        Ok(file_type) => {
                            let path = entry.path();
                            let is_symlink = file_type.is_symlink();
                            if file_type.is_dir() || (is_symlink && path.is_dir()) {
                                if self.recursive == false || is_symlink {
                                    continue;
                                }

                                if self.filter.accept(&path) == false {
                                    continue;
                                }

                                match self.sub_dirs.as_mut() {
                                    Some(sub_dirs) => sub_dirs.push(path),
                                    None => self.sub_dirs = Some(vec![path]),
                                };
                            } else if file_type.is_file() || (is_symlink && path.is_file()) {
                                if self.filter.accept(&path) == false {
                                    continue;
                                }
                                return Some(Ok(path));
                            }
                        },
                        Err(err) => return Some(Err(err)),
                    },
                    Err(err) => return Some(Err(err)),
                },
                None => match self.sub_dirs.as_mut() {
                    None => return None,
                    Some(sub_dirs) => match sub_dirs.len() {
                        0 => return None,
                        _ => match fs::read_dir(sub_dirs.remove(0)) {
                            Ok(new) => self.current = new,
                            Err(err) => return Some(Err(err)),
                        },
                    },
                },
            };
        }
    }

}

/// # Finds files
///
/// This function makes new instance of [`FileDiscovery`][::FileDiscovery]. You should refer to that struct for notes on usage.
///
/// [::FileDiscovery]: struct.FileDiscovery.html
pub fn find_files<P, F>(dir: P, recursive: bool, filter: F) -> io::Result<FileDiscovery<F>> where P: AsRef<Path>, F: filter::Filter {
    Ok(FileDiscovery {
        filter,
        recursive,
        current: fs::read_dir(dir)?,
        sub_dirs: None,
    })
}

/// # Reads bytes from a source
///
/// ## Notes
///
/// - If data to be read exceeds limit, an error is returned. If you don't care about exceeding data, you can use
///   [`Read::take()`][rust::Read::take()].
///
/// ## Examples
///
/// ```
/// use std::{
///     fs::File,
///     io,
///     path::PathBuf,
/// };
///
/// fn test() -> io::Result<()> {
///     let f = file!();
///     let file_size = PathBuf::from(f).metadata()?.len();
///
///     assert_eq!(
///         dia_files::read(File::open(f)?, None)?.len(),
///         dia_files::read(File::open(f)?, Some(file_size as usize))?.len(),
///     );
///
///     dia_files::read(File::open(f)?, Some(0)).unwrap_err();
///
///     Ok(())
/// }
///
/// test().unwrap();
/// ```
///
/// [rust::Read::take()]: https://doc.rust-lang.org/std/io/trait.Read.html#method.take
pub fn read<R>(src: R, limit: Option<usize>) -> io::Result<Vec<u8>> where R: Read {
    let mut reader = BufReader::new(src);
    let mut result = vec![];
    loop {
        let len = {
            let buf = reader.fill_buf()?;

            if buf.is_empty() {
                return Ok(result);
            }

            if let Some(limit) = limit {
                match result.len().checked_add(buf.len()) {
                    Some(new_len) => if new_len > limit {
                        return Err(Error::new(ErrorKind::Other, "Data exceeds limit"));
                    },
                    None => return Err(Error::new(ErrorKind::Other, "Too much data to read")),
                };
            }

            result.extend(buf);
            buf.len()
        };
        reader.consume(len);
    }
}

/// # Reads bytes from a source and converts them into a string
///
/// ## Notes
///
/// - If data to be read exceeds limit, an error is returned. If you don't care about exceeding data, you can use
///   [`Read::take()`][rust::Read::take()].
///
/// ## See also
///
/// [`::read()`](fn.read.html)
///
/// [rust::Read::take()]: https://doc.rust-lang.org/std/io/trait.Read.html#method.take
pub fn read_to_string<R>(src: R, limit: Option<usize>) -> io::Result<String> where R: Read {
    String::from_utf8(read(src, limit)?).map_err(|e| Error::new(ErrorKind::InvalidInput, e))
}

/// # Reads a file
///
/// ## Notes
///
/// - If data to be read exceeds limit, an error is returned. If you don't care about exceeding data, you can use
///   [`Read::take()`][rust::Read::take()].
///
/// ## See also
///
/// [`::read()`](fn.read.html)
///
/// [rust::Read::take()]: https://doc.rust-lang.org/std/io/trait.Read.html#method.take
pub fn read_file<P>(file: P, limit: Option<usize>) -> io::Result<Vec<u8>> where P: AsRef<Path> {
    read(File::open(file)?, limit)
}

/// # Reads a file and converts its content into a string
///
/// ## Notes
///
/// - If data to be read exceeds limit, an error is returned. If you don't care about exceeding data, you can use
///   [`Read::take()`][rust::Read::take()].
///
/// ## See also
///
/// [`::read_to_string()`](fn.read_to_string.html)
///
/// [rust::Read::take()]: https://doc.rust-lang.org/std/io/trait.Read.html#method.take
pub fn read_file_to_string<P>(file: P, limit: Option<usize>) -> io::Result<String> where P: AsRef<Path> {
    read_to_string(File::open(file)?, limit)
}