falco_event/types/path/
absolute_path.rs

1use crate::fields::{FromBytes, FromBytesError, ToBytes};
2use std::ffi::CStr;
3use std::io::Write;
4use typed_path::UnixPath;
5
6impl<'a> FromBytes<'a> for &'a UnixPath {
7    #[inline]
8    fn from_bytes(buf: &mut &'a [u8]) -> Result<Self, FromBytesError> {
9        let buf = <&CStr>::from_bytes(buf)?;
10        Ok(UnixPath::new(buf.to_bytes()))
11    }
12}
13
14impl ToBytes for &UnixPath {
15    #[inline]
16    fn binary_size(&self) -> usize {
17        self.as_bytes().len() + 1
18    }
19
20    #[inline]
21    fn write<W: Write>(&self, mut writer: W) -> std::io::Result<()> {
22        self.as_bytes().write(&mut writer)?;
23        0u8.write(writer)
24    }
25
26    #[inline]
27    fn default_repr() -> impl ToBytes {
28        0u8
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use crate::fields::{FromBytes, ToBytes};
35    use std::str::FromStr;
36    use typed_path::{UnixPath, UnixPathBuf};
37
38    #[test]
39    fn test_absolute_path() {
40        let path = UnixPathBuf::from_str("/foo").unwrap();
41        let mut binary = Vec::new();
42
43        assert_eq!(path.as_path().binary_size(), 5);
44
45        path.as_path().write(&mut binary).unwrap();
46        hexdump::hexdump(binary.as_slice());
47
48        assert_eq!(binary.as_slice(), "/foo\0".as_bytes());
49
50        let mut buf = binary.as_slice();
51        let path = <&UnixPath>::from_bytes(&mut buf).unwrap();
52        assert_eq!(path.to_str().unwrap(), "/foo");
53    }
54}