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
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, self};
use super::{DataLine, DataParseError, Line};

/// Representation of `/etc/hosts`.
pub struct HostsFile<R: BufRead> {
    inner: R,
}

impl HostsFile<BufReader<File>> {
    /// Loads the data from `/etc/hosts`.
    pub fn load() -> io::Result<HostsFile<BufReader<File>>> {
        Ok(HostsFile {
            inner: BufReader::new(File::open("/etc/hosts")?),
        })
    }
}
impl<R: Read> HostsFile<BufReader<R>> {
    /// Loads the data from `/etc/hosts` from a generic reader wrapped in a `BufReader`.
    pub fn read_buffered(reader: R) -> HostsFile<BufReader<R>> {
        HostsFile { inner: BufReader::new(reader) }
    }
}
impl<R: BufRead> HostsFile<R> {
    /// Loads the data from `/etc/hosts` from a generic reader.
    pub fn read(reader: R) -> HostsFile<R> {
        HostsFile { inner: reader }
    }

    /// Iterates over all lines in the file.
    pub fn lines(self) -> Lines<R> {
        Lines { inner: self.inner.lines() }
    }

    /// Iterates over the lines in the file with data.
    pub fn data_lines(self) -> DataLines<R> {
        DataLines { inner: self.inner.lines() }
    }
}

/// Error found when reading a line in `/etc/hosts`.
#[derive(Debug)]
pub enum LineReadError {
    /// The line failed to read.
    Read(io::Error),

    /// The line failed to parse.
    Parse(DataParseError),
}
impl From<io::Error> for LineReadError {
    fn from(err: io::Error) -> LineReadError {
        LineReadError::Read(err)
    }
}
impl From<DataParseError> for LineReadError {
    fn from(err: DataParseError) -> LineReadError {
        LineReadError::Parse(err)
    }
}
impl Error for LineReadError {
    fn description(&self) -> &str {
        match *self {
            LineReadError::Read(ref err) => err.description(),
            LineReadError::Parse(ref err) => err.description(),
        }
    }
    fn cause(&self) -> Option<&Error> {
        Some(match *self {
            LineReadError::Read(ref err) => err,
            LineReadError::Parse(ref err) => err
        })
    }
}
impl fmt::Display for LineReadError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            LineReadError::Read(ref err) => fmt::Display::fmt(err, f),
            LineReadError::Parse(ref err) => fmt::Display::fmt(err, f),
        }
    }
}

/// Iterator over the lines in `/etc/hosts`.
pub struct Lines<R: BufRead> {
    inner: io::Lines<R>,
}
impl<R: BufRead> Iterator for Lines<R> {
    type Item = Result<Line<'static>, LineReadError>;
    fn next(&mut self) -> Option<Result<Line<'static>, LineReadError>> {
        self.inner.next().map(|line| {
            match line {
                Err(err) => return Err(err.into()),
                Ok(line) => return line.parse().map_err(Into::into).map(Line::into_owned),
            }
        })
    }
}

/// Iterator over the lines in `/etc/hosts` with data.
pub struct DataLines<R: BufRead> {
    inner: io::Lines<R>,
}
impl<R: BufRead> Iterator for DataLines<R> {
    type Item = Result<DataLine, LineReadError>;
    fn next(&mut self) -> Option<Result<DataLine, LineReadError>> {
        for line in self.inner.by_ref() {
            match line {
                Err(err) => return Some(Err(err.into())),
                Ok(line) => {
                    match line.parse().map(Line::into_data) {
                        Ok(None) => (),
                        Ok(Some(data)) => return Some(Ok(data)),
                        Err(err) => return Some(Err(err.into())),
                    }
                }
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write;
    use super::*;

    static PRETTY: &str = "\
# basic ones
127.0.0.1  locahost localhost.localdomain
0.0.0.0  allzeros  # nonstandard

# others
8.8.8.8  gdns  # this is the more common one
8.8.4.4  gdns2  # this is the less common one

# comment by itself
";

    static PLAIN: &str = "\
127.0.0.1  locahost localhost.localdomain
0.0.0.0  allzeros
8.8.8.8  gdns
8.8.4.4  gdns2
";

    static BIG: &str = "\
127.0.0.1  locahost
::1  localhost.localdomain
::1  lh
127.0.0.1  lh
0.0.0.0  allzeros
8.8.8.8  gdns
0.0.0.0  lotsazeros
8.8.4.4  gdns2
8.8.8.8  google-dns
";

    static SMALL: &str = "\
0.0.0.0  allzeros lotsazeros
8.8.4.4  gdns2
8.8.8.8  gdns google-dns
127.0.0.1  lh locahost
::1  lh localhost.localdomain
";

    #[test]
    fn lines() {
        let mut rewritten = String::new();
        for line in HostsFile::read_buffered(PRETTY.as_bytes()).lines() {
            let line = line.unwrap();
            writeln!(rewritten, "{}", line).unwrap();
        }
        assert_eq!(rewritten, PRETTY);
    }

    #[test]
    fn data_lines() {
        let mut rewritten = String::new();
        for line in HostsFile::read_buffered(PRETTY.as_bytes()).data_lines() {
            let line = line.unwrap();
            writeln!(rewritten, "{}", line).unwrap();
        }
        assert_eq!(rewritten, PLAIN);
    }
}