1use std::fmt::Display;
2use std::fs;
3use std::io::{Error, ErrorKind, Read, Result, Write};
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6
7#[macro_export]
8macro_rules! method {
9 ($file:tt $with:tt $out:tt) => {
10 pub fn $file(&self) -> Result<$out> {
11 self.$with(stringify!($file))
12 }
13 };
14
15 ($file:expr, $method:tt $with:tt $out:tt) => {
16 pub fn $method(&self) -> Result<$out> {
17 self.$with($file)
18 }
19 };
20}
21
22#[macro_export]
23macro_rules! trait_method {
24 ($file:tt $with:tt $out:tt) => {
25 fn $file(&self) -> Result<$out> {
26 self.$with(stringify!($file))
27 }
28 };
29
30 ($file:expr, $method:tt $with:tt $out:tt) => {
31 fn $method(&self) -> Result<$out> {
32 self.$with($file)
33 }
34 };
35}
36
37#[macro_export]
38macro_rules! set_method {
39 ($file:expr, $method:tt $with:ty) => {
40 pub fn $method(&self, input: $with) -> Result<()> {
41 use numtoa::NumToA;
42 let mut buf = [0u8; 20];
43 self.write_file($file, input.numtoa_str(10, &mut buf))
44 }
45 };
46
47 ($file:expr, $method:tt) => {
48 pub fn $method<B: AsRef<[u8]>>(&self, input: B) -> Result<()> {
49 self.write_file($file, input.as_ref())
50 }
51 };
52}
53
54#[macro_export]
55macro_rules! set_trait_method {
56 ($file:expr, $method:tt $with:ty) => {
57 fn $method(&self, input: $with) -> Result<()> {
58 use numtoa::NumToA;
59 let mut buf = [0u8; 20];
60 self.write_file($file, input.numtoa_str(10, &mut buf))
61 }
62 };
63
64 ($file:expr, $method:tt) => {
65 fn $method<B: AsRef<[u8]>>(&self, input: B) -> Result<()> {
66 self.write_file($file, input.as_ref())
67 }
68 };
69}
70
71pub trait SysClass: Sized {
72 fn base() -> &'static str {
74 "class"
75 }
76 fn class() -> &'static str;
78
79 unsafe fn from_path_unchecked(path: PathBuf) -> Self;
81
82 fn path(&self) -> &Path;
84
85 fn dir() -> PathBuf {
87 Path::new("/sys/").join(Self::base()).join(Self::class())
88 }
89
90 fn from_path(path: &Path) -> Result<Self> {
92 {
93 let parent = path.parent().ok_or_else(|| {
94 Error::new(
95 ErrorKind::InvalidInput,
96 format!("{}: does not have parent", path.display()),
97 )
98 })?;
99
100 let dir = Self::dir();
101 if parent != dir {
102 return Err(Error::new(
103 ErrorKind::InvalidInput,
104 format!("{}: is not a child of {}", path.display(), dir.display()),
105 ));
106 }
107 }
108
109 fs::read_dir(&path)?;
110
111 Ok(unsafe { Self::from_path_unchecked(path.to_owned()) })
112 }
113
114 fn all() -> Result<Vec<Self>> {
116 let mut ret = Vec::new();
117
118 for entry_res in fs::read_dir(Self::dir())? {
119 let entry = entry_res?;
120 ret.push(Self::from_path(&entry.path())?);
121 }
122
123 Ok(ret)
124 }
125
126 fn iter() -> Box<dyn Iterator<Item = Result<Self>>>
128 where
129 Self: 'static,
130 {
131 match fs::read_dir(Self::dir()) {
132 Ok(entries) => Box::new(
133 entries.map(|entry_res| entry_res.and_then(|entry| Self::from_path(&entry.path()))),
134 ),
135 Err(why) => Box::new(::std::iter::once(Err(why))),
136 }
137 }
138
139 fn new(id: &str) -> Result<Self> {
141 Self::from_path(&Self::dir().join(id))
142 }
143
144 fn id(&self) -> &str {
146 self.path()
147 .file_name()
148 .unwrap() .to_str()
150 .unwrap() }
152
153 fn read_file<P: AsRef<Path>>(&self, name: P) -> Result<String> {
155 let mut data = String::new();
156
157 {
158 let path = self.path().join(name.as_ref());
159 let mut file = fs::OpenOptions::new().read(true).open(path)?;
160 file.read_to_string(&mut data)?;
161 }
162
163 Ok(data)
164 }
165
166 fn parse_file<F: FromStr, P: AsRef<Path>>(&self, name: P) -> Result<F>
168 where
169 F::Err: Display,
170 {
171 self.read_file(name.as_ref())?
172 .trim()
173 .parse()
174 .map_err(|err| {
175 Error::new(
176 ErrorKind::InvalidData,
177 format!("{}: {}", name.as_ref().display(), err),
178 )
179 })
180 }
181
182 fn trim_file<P: AsRef<Path>>(&self, name: P) -> Result<String> {
184 let data = self.read_file(name)?;
185 Ok(data.trim().to_string())
186 }
187
188 fn write_file<P: AsRef<Path>, S: AsRef<[u8]>>(&self, name: P, data: S) -> Result<()> {
190 {
191 let path = self.path().join(name.as_ref());
192 let mut file = fs::OpenOptions::new().write(true).open(path)?;
193 file.write_all(data.as_ref())?
194 }
195
196 Ok(())
197 }
198}