use crate::error::{Error, Result};
use crate::util::parse;
use std::os::unix::ffi::OsStrExt;
#[derive(Debug)]
pub struct CgroupEntry {
pub hierarchy: u32,
pub controllers: Vec<Box<str>>,
pub path: std::path::PathBuf,
}
impl CgroupEntry {
pub fn parse_all(bytes: &[u8]) -> Result<Vec<Self>> {
let mut entries = Vec::new();
for line in bytes.split(|&b| b == b'\n').filter(|l| !l.is_empty()) {
entries.push(Self::parse_line(line)?);
}
Ok(entries)
}
fn parse_line(line: &[u8]) -> Result<Self> {
let fields: Vec<&[u8]> = line.splitn(3, |&b| b == b':').collect();
if fields.len() < 3 {
return Err(Error::Parse {
path: std::path::PathBuf::from("<cgroup>"),
line: 0,
msg: "not enough fields",
});
}
let hierarchy = parse::parse_dec_u32_fast(fields[0])?;
let controllers_raw = fields[1];
let controllers: Vec<Box<str>> = if controllers_raw.is_empty() {
Vec::new()
} else {
controllers_raw
.split(|&b| b == b',')
.filter(|c| !c.is_empty())
.map(|c| {
std::str::from_utf8(c)
.map(str::to_owned)
.map(String::into_boxed_str)
.map_err(|_| Error::Parse {
path: std::path::PathBuf::from("<cgroup>"),
line: 0,
msg: "controller name is not valid UTF-8",
})
})
.collect::<Result<Vec<_>>>()?
};
let path = std::path::PathBuf::from(std::ffi::OsStr::from_bytes(fields[2]));
Ok(CgroupEntry {
hierarchy,
controllers,
path,
})
}
}