falco_event/types/path/
relative_path.rs1use crate::fields::{FromBytes, FromBytesError, ToBytes};
2use std::fmt::{Debug, Formatter};
3use std::io::Write;
4use typed_path::UnixPath;
5
6#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
12pub struct RelativePath<'a>(pub &'a UnixPath);
13
14impl<'a> ToBytes for RelativePath<'a> {
15 #[inline]
16 fn binary_size(&self) -> usize {
17 self.0.binary_size()
18 }
19
20 #[inline]
21 fn write<W: Write>(&self, writer: W) -> std::io::Result<()> {
22 self.0.write(writer)
23 }
24
25 #[inline]
26 fn default_repr() -> impl ToBytes {
27 <&'a UnixPath>::default_repr()
28 }
29}
30
31impl<'a> FromBytes<'a> for RelativePath<'a> {
32 #[inline]
33 fn from_bytes(buf: &mut &'a [u8]) -> Result<Self, FromBytesError> {
34 Ok(Self(<&'a UnixPath>::from_bytes(buf)?))
35 }
36}
37
38impl Debug for RelativePath<'_> {
39 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
40 write!(f, "<...>{}", self.0.display())
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use std::str::FromStr;
47
48 use crate::fields::{FromBytes, ToBytes};
49 use crate::types::path::relative_path::RelativePath;
50
51 use typed_path::UnixPathBuf;
52
53 #[test]
54 fn test_relative_path() {
55 let path = UnixPathBuf::from_str("/foo").unwrap();
56 let rel_path = RelativePath(path.as_path());
57 let mut binary = Vec::new();
58
59 rel_path.write(&mut binary).unwrap();
60 hexdump::hexdump(binary.as_slice());
61
62 assert_eq!(binary.as_slice(), "/foo\0".as_bytes());
63
64 let mut buf = binary.as_slice();
65 let path = RelativePath::from_bytes(&mut buf).unwrap();
66 assert_eq!(path.0.to_str().unwrap(), "/foo");
67 }
68}