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
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "windows")]
mod windows;
use std::path::PathBuf;
#[cfg(target_os = "linux")]
use linux as sys;
#[cfg(target_os = "macos")]
use macos as sys;
#[cfg(target_os = "windows")]
use windows as sys;
#[derive(Debug, Clone)]
pub struct MountInfo {
pub path: PathBuf,
pub avail: Option<u64>,
pub free: Option<u64>,
pub size: Option<u64>,
pub name: Option<String>,
pub format: Option<String>,
pub readonly: Option<bool>,
pub dummy: bool,
__priv: (),
}
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
WindowsUtf16Error,
WindowsVolumeIterError(u32),
WindowsMountIterError(u32),
LinuxIoError(std::io::Error),
LinuxPathParseError,
MacOsGetfsstatError(i32),
MacOsUtf8Error,
}
impl std::error::Error for Error {}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::WindowsUtf16Error => f.write_str("invalid utf16 path"),
Error::WindowsVolumeIterError(code) => {
write!(f, "unable to get list of volumes: {}", code)
}
Error::WindowsMountIterError(code) => {
write!(f, "unable to get list of mounts: {}", code)
}
Error::LinuxIoError(err) => write!(f, "failed to read /proc/mounts: {}", err),
Error::LinuxPathParseError => write!(f, "failed to parse path"),
Error::MacOsGetfsstatError(err) => write!(f, "getfsstat failed: {}", err),
Error::MacOsUtf8Error => write!(f, "invalid utf8 format"),
}
}
}
pub fn mountinfos() -> Result<Vec<MountInfo>, Error> {
sys::mountinfos()
}
pub fn mountpaths() -> Result<Vec<PathBuf>, Error> {
sys::mountpaths()
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
fn root() -> &'static Path {
if cfg!(target_os = "windows") {
Path::new("C:\\")
} else {
Path::new("/")
}
}
#[test]
fn mountpaths_works() {
let paths = mountpaths().unwrap();
assert!(paths.len() > 0);
assert!(paths.iter().any(|p| p == root()));
for mountpath in &paths {
eprintln!("{:?}", mountpath);
}
}
#[test]
fn mountinfosworks() {
let infos = mountinfos().unwrap();
assert!(infos.len() > 0);
assert!(infos.iter().any(|i| if i.path == root() {
assert!(i.size.unwrap_or_default() > 1024 * 1024); assert!(i.avail.unwrap_or_default() < i.size.unwrap_or_default());
assert!(i.free.unwrap_or_default() < i.size.unwrap_or_default());
true
} else {
false
}));
for mountinfo in &infos {
eprintln!("{:?}", mountinfo);
}
}
}