sysinfo/unix/linux/
utils.rs1#[cfg(any(feature = "disk", feature = "system"))]
4use std::fs::File;
5#[cfg(any(feature = "disk", feature = "system"))]
6use std::io::{self, Read, Seek};
7#[cfg(any(feature = "disk", feature = "system"))]
8use std::path::Path;
9
10#[cfg(feature = "system")]
11pub(crate) fn get_all_data_from_file(file: &mut File, size: usize) -> io::Result<Vec<u8>> {
12 let mut buf = Vec::with_capacity(size);
13 file.rewind()?;
14 file.read_to_end(&mut buf)?;
15 Ok(buf)
16}
17
18#[cfg(any(feature = "disk", feature = "system"))]
19pub(crate) fn get_all_utf8_data_from_file(file: &mut File, size: usize) -> io::Result<String> {
20 let mut buf = String::with_capacity(size);
21 file.rewind()?;
22 file.read_to_string(&mut buf)?;
23 Ok(buf)
24}
25
26#[cfg(any(feature = "disk", feature = "system"))]
27pub(crate) fn get_all_utf8_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Result<String> {
28 let mut file = File::open(file_path.as_ref())?;
29 get_all_utf8_data_from_file(&mut file, size)
30}
31
32#[cfg(feature = "system")]
33#[allow(clippy::useless_conversion)]
34pub(crate) fn realpath(path: &Path) -> Option<std::path::PathBuf> {
35 match std::fs::read_link(path) {
36 Ok(path) => Some(path),
37 Err(_e) => {
38 sysinfo_debug!("failed to get real path for {:?}: {:?}", path, _e);
39 None
40 }
41 }
42}
43
44#[cfg(feature = "system")]
47pub(crate) struct PathHandler(std::path::PathBuf);
48
49#[cfg(feature = "system")]
50impl PathHandler {
51 pub(crate) fn new(path: &Path) -> Self {
52 Self(path.join("a"))
55 }
56}
57
58#[cfg(feature = "system")]
59pub(crate) trait PathPush {
60 fn join(&mut self, p: &str) -> &Path;
61}
62
63#[cfg(feature = "system")]
64impl PathPush for PathHandler {
65 fn join(&mut self, p: &str) -> &Path {
66 self.0.pop();
67 self.0.push(p);
68 self.0.as_path()
69 }
70}
71
72#[cfg(feature = "system")]
74impl PathPush for std::path::PathBuf {
75 fn join(&mut self, p: &str) -> &Path {
76 self.push(p);
77 self.as_path()
78 }
79}
80
81#[cfg(feature = "system")]
82pub(crate) fn to_u64(v: &[u8]) -> u64 {
83 let mut x = 0;
84
85 for c in v {
86 x *= 10;
87 x += u64::from(c - b'0');
88 }
89 x
90}
91
92#[cfg(feature = "disk")]
94pub(crate) fn to_cpath(path: &std::path::Path) -> Vec<u8> {
95 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
96
97 let path_os: &OsStr = path.as_ref();
98 let mut cpath = path_os.as_bytes().to_vec();
99 cpath.push(0);
100 cpath
101}