proc_mounts/mounts/
iter.rs

1use super::MountInfo;
2use std::{
3    fs::File,
4    io::{self, BufRead, BufReader},
5    path::Path,
6    str::FromStr,
7};
8
9/// Iteratively parse the `/proc/mounts` file.
10pub struct MountIter<R> {
11    file:   R,
12    buffer: String,
13}
14
15impl MountIter<BufReader<File>> {
16    pub fn new() -> io::Result<Self> { Self::new_from_file("/proc/mounts") }
17
18    /// Read mounts from any mount-tab-like file.
19    pub fn new_from_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
20        Ok(Self::new_from_reader(BufReader::new(File::open(path)?)))
21    }
22}
23
24impl<R: BufRead> MountIter<R> {
25    /// Read mounts from any in-memory buffer.
26    pub fn new_from_reader(readable: R) -> Self {
27        Self { file: readable, buffer: String::with_capacity(512) }
28    }
29
30    /// Iterator-based variant of `source_mounted_at`.
31    ///
32    /// Returns true if the `source` is mounted at the given `dest`.
33    ///
34    /// Due to iterative parsing of the mount file, an error may be returned.
35    pub fn source_mounted_at<D: AsRef<Path>, P: AsRef<Path>>(
36        source: D,
37        path: P,
38    ) -> io::Result<bool> {
39        let source = source.as_ref();
40        let path = path.as_ref();
41
42        let mut is_found = false;
43
44        let mounts = MountIter::new()?;
45        for mount in mounts {
46            let mount = mount?;
47            if mount.source == source {
48                is_found = mount.dest == path;
49                break;
50            }
51        }
52
53        Ok(is_found)
54    }
55}
56
57impl<R: BufRead> Iterator for MountIter<R> {
58    type Item = io::Result<MountInfo>;
59
60    fn next(&mut self) -> Option<Self::Item> {
61        loop {
62            self.buffer.clear();
63            match self.file.read_line(&mut self.buffer) {
64                Ok(read) if read == 0 => return None,
65                Ok(_) => {
66                    let line = self.buffer.trim_start();
67                    if !(line.starts_with('#') || line.is_empty()) {
68                        return Some(MountInfo::from_str(line));
69                    }
70                }
71                Err(why) => return Some(Err(why)),
72            }
73        }
74    }
75}