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
pub mod cpu;
pub mod disks;
pub mod host;
pub mod memory;
mod models;
pub use models::*;
use libc::{c_char, statvfs, PATH_MAX};
#[cfg(target_os = "macos")]
use mach::vm_types::integer_t;
use std::ffi::CStr;
#[cfg(target_os = "linux")]
use std::fs;
use std::io::{Error, ErrorKind};
#[allow(non_camel_case_types)]
#[cfg(target_os = "macos")]
type host_flavor_t = integer_t;
#[allow(non_camel_case_types)]
#[cfg(target_os = "macos")]
type host_info64_t = *mut integer_t;
#[cfg(target_os = "macos")]
lazy_static::lazy_static! {
static ref PAGE_SIZE: u64 = {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as u64
}
};
}
#[cfg(target_os = "linux")]
pub(crate) fn read_and_trim(path: &str) -> Result<String, Error> {
let content = fs::read_to_string(path)?;
Ok(content.trim().to_owned())
}
pub(crate) fn is_physical_filesys(filesysteme: &str) -> bool {
match filesysteme {
"ext2" => true,
"ext3" => true,
"ext4" => true,
"vfat" => true,
"ntfs" => true,
"zfs" => true,
"hfs" => true,
"reiserfs" => true,
"reiser4" => true,
"exfat" => true,
"f2fs" => true,
"hfsplus" => true,
"jfs" => true,
"btrfs" => true,
"minix" => true,
"nilfs" => true,
"xfs" => true,
"apfs" => true,
"fuseblk" => true,
_ => false,
}
}
pub(crate) fn disk_usage<P>(path: P) -> Result<(u64, u64), Error>
where
P: AsRef<[u8]>,
{
let mut statvfs = std::mem::MaybeUninit::<statvfs>::uninit();
let mpath = path.as_ref();
let mpath_len = mpath.len();
if mpath_len >= PATH_MAX as usize {
return Err(Error::new(ErrorKind::Other, "Invalid path lenght"));
}
let mut buf = [0u8; PATH_MAX as usize];
unsafe {
std::ptr::copy_nonoverlapping(mpath.as_ptr(), buf.as_mut_ptr(), mpath_len);
if libc::statvfs(
CStr::from_ptr(buf.as_ptr() as *const c_char).as_ptr(),
statvfs.as_mut_ptr(),
) == -1
{
return Err(Error::last_os_error());
}
}
let statvfs = unsafe { statvfs.assume_init() };
let total = statvfs.f_blocks as u64 * statvfs.f_bsize as u64;
let free = statvfs.f_bavail as u64 * statvfs.f_bsize as u64;
Ok((total, free))
}
#[allow(dead_code)]
#[inline]
pub(crate) fn to_str_mut<'a>(s: *mut c_char) -> &'a str {
unsafe {
let res = CStr::from_ptr(s).to_bytes();
std::str::from_utf8_unchecked(res)
}
}
#[inline]
pub(crate) fn to_str<'a>(s: *const c_char) -> &'a str {
unsafe {
let res = CStr::from_ptr(s).to_bytes();
std::str::from_utf8_unchecked(res)
}
}