mprober_lib/volume/
mounts.rs

1use std::{collections::HashMap, io::ErrorKind, path::Path, str::from_utf8_unchecked};
2
3use crate::scanner_rust::{generic_array::typenum::U1024, Scanner, ScannerError};
4
5/// Get mounting points of all block devices by reading the `/proc/mounts` file.
6///
7/// ```rust
8/// use mprober_lib::volume;
9///
10/// let mounts = volume::get_mounts().unwrap();
11///
12/// println!("{mounts:#?}");
13/// ```
14pub fn get_mounts() -> Result<HashMap<String, Vec<String>>, ScannerError> {
15    let mut sc: Scanner<_, U1024> = Scanner::scan_path2("/proc/mounts")?;
16
17    let mut mounts: HashMap<String, Vec<String>> = HashMap::with_capacity(1);
18
19    while let Some(device_path) = sc.next_raw()? {
20        if device_path.starts_with(b"/dev/") {
21            let device = {
22                let device = &device_path[5..];
23
24                if device.starts_with(b"mapper/") {
25                    let device_path =
26                        Path::new(unsafe { from_utf8_unchecked(device_path.as_ref()) })
27                            .canonicalize()?;
28
29                    device_path.file_name().unwrap().to_string_lossy().into_owned()
30                } else {
31                    unsafe { from_utf8_unchecked(device) }.to_string()
32                }
33            };
34
35            let point = unsafe {
36                String::from_utf8_unchecked(sc.next_raw()?.ok_or(ErrorKind::UnexpectedEof)?)
37            };
38
39            match mounts.get_mut(&device) {
40                Some(devices) => {
41                    devices.push(point);
42                },
43                None => {
44                    mounts.insert(device, vec![point]);
45                },
46            }
47        }
48
49        sc.drop_next_line()?.ok_or(ErrorKind::UnexpectedEof)?;
50    }
51
52    Ok(mounts)
53}