use super::*;
macro_rules! parse_integers {
($($ty:ident: $name:ident),+) => {
$(
pub(crate) fn $name(bytes: &[u8]) -> Option<$ty> {
let mut num: $ty = 0;
for &b in bytes {
if !b.is_ascii_digit() {
return None;
}
num = num.checked_mul(10)?.checked_add((b - b'0') as $ty)?;
}
Some(num)
}
)+
}
}
parse_integers!(
u64: parse_ascii_checked_u64,
c_ulong: parse_ascii_checked_culong,
usize: parse_ascii_checked_usize,
pid_t: parse_ascii_checked_pid_t,
uid_t: parse_ascii_checked_uid_t
);
pub(crate) fn split_content(data: &[u8]) -> Vec<OsString> {
let mut out = Vec::with_capacity(10);
for part in data.split(|c| *c == 0) {
if !part.is_empty() {
out.push(OsStr::from_bytes(part).to_os_string());
}
}
out
}
#[cfg_attr(test, derive(PartialEq, Debug))]
pub(crate) struct Parts {
pub(crate) short_exe: OsString,
pub(crate) status: ProcessStatus,
pub(crate) parent_pid: Option<pid_t>,
pub(crate) flags: Option<c_ulong>,
pub(crate) user_time: u64,
pub(crate) system_time: u64,
pub(crate) start_time: u64,
pub(crate) virtual_size: u64,
pub(crate) resident_set_size: u64,
}
pub(crate) fn parse_stat_file(data: &[u8], start_time_raw: Option<u64>) -> Option<Parts> {
let data = data.splitn(2, |&b| b == b' ').nth(1)?;
if data.first() != Some(&b'(') {
return None;
}
let pos = data.iter().rposition(|&b| b == b')')?;
if pos == 0 {
return None;
}
let short_exe = &data[1..pos];
let mut data = data[pos + 1..]
.split(|c| *c == b' ')
.filter(|p| !p.is_empty());
let status = data
.next()
.and_then(|part| part.first().copied().map(ProcessStatus::from))
.unwrap_or(ProcessStatus::Unknown(0));
let parent_pid = data.next().and_then(parse_ascii_checked_pid_t);
let flags = data
.nth(ProcIndex::Flags as usize - ProcIndex::ParentPid as usize - 1)
.and_then(parse_ascii_checked_culong);
let user_time = data
.nth(ProcIndex::UserTime as usize - ProcIndex::Flags as usize - 1)
.and_then(parse_ascii_checked_u64)
.unwrap_or(0);
let system_time = data.next().and_then(parse_ascii_checked_u64).unwrap_or(0);
let start_time = data
.nth(ProcIndex::StartTime as usize - ProcIndex::SystemTime as usize - 1)
.and_then(parse_ascii_checked_u64)
.unwrap_or(0);
let virtual_size = data.next().and_then(parse_ascii_checked_u64).unwrap_or(0);
let resident_set_size = data.next().and_then(parse_ascii_checked_u64).unwrap_or(0);
Some(Parts {
status,
parent_pid,
flags,
user_time,
system_time,
start_time,
virtual_size,
resident_set_size,
short_exe: if start_time_raw.is_some_and(|raw| start_time == raw) {
OsString::new()
} else {
OsStr::from_bytes(short_exe).to_os_string()
},
})
}