summaryrefslogtreecommitdiffstats
path: root/src/unix.rs
blob: d549b63bbdf0f38a224320b91a6f896cc85e16da (plain)
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
use std::{
    fs::File,
    io::{BufRead, BufReader, Error},
};

use crate::Session;

pub struct Hosts(Vec<Session>);

impl Hosts {
    pub fn open() -> Result<Self, Error> {
        File::open("/etc/hosts").map(Self::parse_file).map(Self)
    }

    fn parse_file(file: File) -> Vec<Session> {
        BufReader::new(file)
            .lines()
            .flatten()
            .filter_map(Self::parse_line)
            .collect()
    }

    fn parse_line(line: String) -> Option<Session> {
        line.split_whitespace()
            .take_while(|s| !s.starts_with('#'))
            .last()
            // Skip BOM
            .filter(|&s| s != "\u{feff}")
            .map(Session::discover)
    }
}

impl IntoIterator for Hosts {
    type Item = Session;

    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}