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
use std::fmt::Display;
use std::fs;
use std::io::{Error, ErrorKind, Read, Result, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
#[macro_export]
macro_rules! method {
($file:tt $with:tt $out:tt) => {
pub fn $file(&self) -> Result<$out> {
self.$with(stringify!($file))
}
};
($file:expr, $method:tt $with:tt $out:tt) => {
pub fn $method(&self) -> Result<$out> {
self.$with($file)
}
};
}
pub trait SysClass: Sized {
fn class() -> &'static str;
unsafe fn from_path_unchecked(path: PathBuf) -> Self;
fn path(&self) -> &Path;
fn dir() -> PathBuf {
Path::new("/sys/class").join(Self::class())
}
fn from_path(path: &Path) -> Result<Self> {
{
let parent = path.parent().ok_or(Error::new(
ErrorKind::InvalidInput,
format!("{}: does not have parent", path.display())
))?;
let dir = Self::dir();
if parent != dir {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("{}: is not a child of {}", path.display(), dir.display())
));
}
}
fs::read_dir(&path)?;
Ok(unsafe { Self::from_path_unchecked(path.to_owned()) })
}
fn all() -> Result<Vec<Self>> {
let mut ret = Vec::new();
for entry_res in fs::read_dir(Self::dir())? {
let entry = entry_res?;
ret.push(Self::from_path(&entry.path())?);
}
Ok(ret)
}
fn new(id: &str) -> Result<Self> {
Self::from_path(&Self::dir().join(id))
}
fn id(&self) -> &str {
self.path()
.file_name().unwrap() .to_str().unwrap() }
fn read_file<P: AsRef<Path>>(&self, name: P) -> Result<String> {
let mut data = String::new();
{
let path = self.path().join(name.as_ref());
let mut file = fs::OpenOptions::new().read(true).open(path)?;
file.read_to_string(&mut data)?;
}
Ok(data)
}
fn parse_file<F: FromStr, P: AsRef<Path>>(&self, name: P) -> Result<F> where F::Err: Display {
self.read_file(name)?.trim().parse().map_err(|err| {
Error::new(
ErrorKind::InvalidData,
format!("{}", err)
)
})
}
fn trim_file<P: AsRef<Path>>(&self, name: P) -> Result<String> {
let data = self.read_file(name)?;
Ok(data.trim().to_string())
}
fn write_file<P: AsRef<Path>, S: AsRef<[u8]>>(&self, name: P, data: S) -> Result<()> {
{
let path = self.path().join(name.as_ref());
let mut file = fs::OpenOptions::new().write(true).open(path)?;
file.write_all(data.as_ref())?
}
Ok(())
}
}