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 {
    /// Return the class of the sys object, the name of a folder in /sys/class
    fn class() -> &'static str;

    /// Create a sys object from an absolute path without checking path for validity
    unsafe fn from_path_unchecked(path: PathBuf) -> Self;

    /// Return the path of the sys object
    fn path(&self) -> &Path;

    /// Return the path to the sys objects, the full path of a folder in /sys/class
    fn dir() -> PathBuf {
        Path::new("/sys/class").join(Self::class())
    }

    /// Create a sys object from a path, checking it for validity
    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()) })
    }

    /// Retrieve all of the object instances of a sys class
    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)
    }

    /// Create a sys object by id, checking it for validity
    fn new(id: &str) -> Result<Self> {
        Self::from_path(&Self::dir().join(id))
    }

    /// Return the id of the sys object
    fn id(&self) -> &str {
        self.path()
            .file_name().unwrap() // A valid path does not end in .., so safe
            .to_str().unwrap() // A valid path must be valid UTF-8, so safe
    }

    /// Read a file underneath the sys object
    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)
    }

    /// Parse a number from a file underneath the sys object
    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)
            )
        })
    }

    /// Read a file underneath the sys object and trim whitespace
    fn trim_file<P: AsRef<Path>>(&self, name: P) -> Result<String> {
        let data = self.read_file(name)?;
        Ok(data.trim().to_string())
    }

    /// Write a file underneath the sys object
    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(())
    }
}