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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// linux/ctl_iter.rs

use super::ctl::Ctl;
use ctl_error::SysctlError;
use traits::Sysctl;

/// An iterator over Sysctl entries.
pub struct CtlIter {
    direntries: Vec<walkdir::DirEntry>,
    base: String,
    cur_idx: usize,
}

impl CtlIter {
    /// Return an iterator over the complete sysctl tree.
    pub fn root() -> Self {
        let entries: Vec<walkdir::DirEntry> = walkdir::WalkDir::new("/proc/sys")
            .sort_by(|a, b| a.path().cmp(b.path()))
            .follow_links(false)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().is_file())
            .collect();
        CtlIter {
            direntries: entries,
            base: "/proc/sys".to_owned(),
            cur_idx: 0,
        }
    }

    /// Return an iterator over all sysctl entries below the given node.
    pub fn below(node: Ctl) -> Self {
        let root = node.path();
        let entries: Vec<walkdir::DirEntry> = walkdir::WalkDir::new(&root)
            .sort_by(|a, b| a.path().cmp(b.path()))
            .follow_links(false)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().is_file())
            .collect();
        CtlIter {
            direntries: entries,
            base: root,
            cur_idx: 0,
        }
    }
}

impl Iterator for CtlIter {
    type Item = Result<Ctl, SysctlError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cur_idx >= self.direntries.len() {
            return None;
        }

        let e: &walkdir::DirEntry = &self.direntries[self.cur_idx];
        self.cur_idx += 1;

        // We continue iterating as long as the oid starts with the base
        if let Some(path) = e.path().to_str() {
            if path.starts_with(&self.base) {
                Some(Ctl::new(path))
            } else {
                None
            }
        } else {
            Some(Err(SysctlError::ParseError))
        }
    }
}

/// Ctl implements the IntoIterator trait to allow for easy iteration
/// over nodes.
///
/// # Example
///
/// ```
/// # use sysctl::Sysctl;
/// #
/// let kern = sysctl::Ctl::new("kernel");
/// for ctl in kern {
///     println!("{}", ctl.name().unwrap());
/// }
/// ```
impl IntoIterator for Ctl {
    type Item = Result<Ctl, SysctlError>;
    type IntoIter = CtlIter;

    fn into_iter(self: Self) -> Self::IntoIter {
        CtlIter::below(self)
    }
}

#[cfg(test)]
mod tests {
    use crate::Sysctl;

    #[test]
    fn ctl_iter_iterate_all() {
        let root = crate::CtlIter::root();
        let all_ctls: Vec<super::Ctl> = root.into_iter().filter_map(Result::ok).collect();
        assert_ne!(all_ctls.len(), 0);
        for ctl in &all_ctls {
            println!("{:?}", ctl.name());
        }
    }

    #[test]
    fn ctl_iter_below_compare_outputs() {
        let output = std::process::Command::new("sysctl")
            .arg("user")
            .output()
            .expect("failed to execute process");
        let expected = String::from_utf8_lossy(&output.stdout);

        let node = crate::Ctl::new("user").expect("could not get node");
        let ctls = crate::CtlIter::below(node);
        let mut actual: Vec<String> = vec![];

        for ctl in ctls {
            let ctl = match ctl {
                Err(_) => panic!("ctl error"),
                Ok(s) => s,
            };

            let name = match ctl.name() {
                Ok(s) => s,
                Err(_) => panic!("get ctl name"),
            };

            match ctl.value_type().expect("could not get value type") {
                crate::CtlType::String => {
                    actual.push(format!(
                        "{} = {}",
                        name,
                        ctl.value_string()
                            .expect(&format!("could not get value as string for {}", name))
                    ));
                }
                _ => panic!("sysctl not string type"),
            };
        }
        assert_eq!(actual.join("\n").trim(), expected.trim());
    }
}