use std::borrow::Cow;
use std::ffi::OsStr;
use std::fmt;
use crate::prelude::*;
used_in_docs!(OsStr);
#[derive(Clone)]
pub struct Comm<'a> {
pub pid: u32,
pub tid: u32,
pub comm: Cow<'a, [u8]>,
}
impl<'a> Comm<'a> {
#[cfg(unix)]
pub fn comm_os(&self) -> &OsStr {
use std::os::unix::ffi::OsStrExt;
OsStrExt::from_bytes(&self.comm)
}
pub fn into_owned(self) -> Comm<'static> {
Comm {
comm: self.comm.into_owned().into(),
..self
}
}
}
impl<'p> Parse<'p> for Comm<'p> {
fn parse<B, E>(p: &mut Parser<B, E>) -> ParseResult<Self>
where
E: Endian,
B: ParseBuf<'p>,
{
Ok(Self {
pid: p.parse()?,
tid: p.parse()?,
comm: p.parse_rest_trim_nul()?,
})
}
}
impl fmt::Debug for Comm<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Comm")
.field("pid", &self.pid)
.field("tid", &self.tid)
.field("comm", &crate::util::fmt::ByteStr(&self.comm))
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::endian::Little;
#[test]
fn test_parse() {
#[rustfmt::skip]
let bytes: &[u8] = &[
0x10, 0x10, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00,
b't', b'e', b's', b't', 0x00, 0x00, 0x00, 0x00
];
let mut parser: Parser<_, Little> = Parser::new(bytes, ParseConfig::default());
let comm: Comm = parser.parse().unwrap();
assert_eq!(comm.pid, 0x1010);
assert_eq!(comm.tid, 0x0500);
assert_eq!(&*comm.comm, b"test");
}
}