liboj-cgroups 0.1.0

Cgroup wrapping for liboj
Documentation
//! AttrFile trait provide an interface to read an attribute from or write an attribute to a file.
//!
//! This is widely used in cgroup filesystem.
use std::collections::HashMap;
use std::io;
use std::ops::Deref;

use lazy_static::lazy_static;
use regex::Regex;

/// A file which can be written and read.
pub trait AttrFile<T, U: ?Sized = T>: ReadAttr<T> + WriteAttr<U> {}

/// A file which can read `T` from the file.
pub trait ReadAttr<T> {
    /// Read an attribute from the file.
    fn read(&self) -> io::Result<T>;
}

/// A file which can write `T` into the file.
pub trait WriteAttr<T: ?Sized> {
    /// Write an attribute into the file.
    fn write(&self, attr: &T) -> io::Result<()>;
}

impl<F, T, U> AttrFile<T, U> for F
where
    F: ReadAttr<T> + WriteAttr<U>,
    U: ?Sized,
{
}

pub trait ResetAttr {
    fn reset(&self) -> io::Result<()>;
}

pub struct StatMap<'a>(HashMap<&'a str, &'a str>);

impl<'a> From<&'a str> for StatMap<'a> {
    fn from(s: &'a str) -> StatMap<'a> {
        lazy_static! {
            static ref RE: Regex = Regex::new(r"(?m)^(?P<key>[_a-z]+) (?P<value>\d+)$").unwrap();
        }
        let mut res = HashMap::new();
        for m in RE.captures_iter(s) {
            res.insert(
                m.name("key").unwrap().as_str(),
                m.name("value").unwrap().as_str(),
            );
        }
        StatMap(res)
    }
}

impl<'a> Deref for StatMap<'a> {
    type Target = HashMap<&'a str, &'a str>;

    fn deref(&self) -> &HashMap<&'a str, &'a str> {
        &self.0
    }
}

macro_rules! stat_attr {
    ($map: ident, $stat: ident, [$($name: ident),+]) => {
        $stat {
            $($name: match $map.get(stringify!($name)).map(|s| s.parse()) {
                Some(Ok($name)) => $name,
                Some(Err(_)) | None => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("failed to parse {}", stringify!($name),),
                    ));
                }
            },)*
       }
    };
}