use crate::TagType;
use core::mem;
use core::slice;
use core::str;
#[derive(Clone, Copy, Debug)]
#[repr(C, packed)] pub struct CommandLineTag {
typ: TagType,
size: u32,
string: u8,
}
impl CommandLineTag {
pub fn command_line(&self) -> Result<&str, str::Utf8Error> {
let strlen = self.size as usize - mem::size_of::<CommandLineTag>();
let bytes = unsafe { slice::from_raw_parts((&self.string) as *const u8, strlen) };
str::from_utf8(bytes)
}
}
#[cfg(test)]
mod tests {
use crate::TagType;
const MSG: &str = "hello";
fn get_bytes() -> std::vec::Vec<u8> {
let size = (4 + 4 + MSG.as_bytes().len() + 1) as u32;
[
&((TagType::Cmdline as u32).to_ne_bytes()),
&size.to_ne_bytes(),
MSG.as_bytes(),
&[0],
]
.iter()
.flat_map(|bytes| bytes.iter())
.copied()
.collect()
}
#[test]
fn test_parse_str() {
let tag = get_bytes();
let tag = unsafe {
tag.as_ptr()
.cast::<super::CommandLineTag>()
.as_ref()
.unwrap()
};
assert_eq!({ tag.typ }, TagType::Cmdline);
assert_eq!(tag.command_line().expect("must be valid UTF-8"), MSG);
}
}