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")]
35pub(crate) struct PathHandler(std::path::PathBuf);
36
37#[cfg(feature = "system")]
38impl PathHandler {
39 pub(crate) fn new(path: &Path) -> Self {
40 Self(path.join("a"))
44 }
45
46 pub(crate) fn as_path(&self) -> &Path {
47 &self.0
48 }
49}
50
51#[cfg(feature = "system")]
52pub(crate) trait PathPush {
53 fn replace_and_join(&mut self, p: &str) -> &Path;
54}
55
56#[cfg(feature = "system")]
57impl PathPush for PathHandler {
58 fn replace_and_join(&mut self, p: &str) -> &Path {
59 self.0.pop();
60 self.0.push(p);
61 self.as_path()
62 }
63}
64
65#[cfg(feature = "system")]
67impl PathPush for std::path::PathBuf {
68 fn replace_and_join(&mut self, p: &str) -> &Path {
69 self.push(p);
70 self.as_path()
71 }
72}
73
74#[cfg(feature = "system")]
75pub(crate) fn to_u64(v: &[u8]) -> u64 {
76 let mut x = 0;
77
78 for c in v {
79 x *= 10;
80 x += u64::from(c - b'0');
81 }
82 x
83}
84
85#[cfg(feature = "disk")]
87pub(crate) fn to_cpath(path: &std::path::Path) -> Vec<u8> {
88 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
89
90 let path_os: &OsStr = path.as_ref();
91 let mut cpath = path_os.as_bytes().to_vec();
92 cpath.push(0);
93 cpath
94}