falco_event/types/path/
absolute_path.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::ffi::{CStr, OsStr};
use std::fmt::Formatter;
use std::io::Write;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};

use crate::event_derive::{FromBytes, FromBytesResult, ToBytes};
use crate::types::format::Format;
use crate::types::{Borrow, Borrowed};

impl<'a> FromBytes<'a> for &'a Path {
    fn from_bytes(buf: &mut &'a [u8]) -> FromBytesResult<Self> {
        let buf = <&CStr>::from_bytes(buf)?;
        let osstr = OsStr::from_bytes(buf.to_bytes());
        Ok(Path::new(osstr))
    }
}

impl ToBytes for &Path {
    fn binary_size(&self) -> usize {
        self.as_os_str().len() + 1
    }

    fn write<W: Write>(&self, mut writer: W) -> std::io::Result<()> {
        self.as_os_str().as_bytes().write(&mut writer)?;
        0u8.write(writer)
    }

    fn default_repr() -> impl ToBytes {
        0u8
    }
}

impl<F> Format<F> for &Path
where
    for<'a> &'a [u8]: Format<F>,
{
    fn format(&self, fmt: &mut Formatter) -> std::fmt::Result {
        let bytes = self.as_os_str().as_bytes();
        bytes.format(fmt)
    }
}

impl Borrowed for Path {
    type Owned = PathBuf;
}

impl Borrow for PathBuf {
    type Borrowed<'a> = &'a Path;

    fn borrow(&self) -> Self::Borrowed<'_> {
        self.as_path()
    }
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};
    use std::str::FromStr;

    use crate::event_derive::{FromBytes, ToBytes};

    #[test]
    fn test_absolute_path() {
        let path = PathBuf::from_str("/foo").unwrap();
        let mut binary = Vec::new();

        path.as_path().write(&mut binary).unwrap();
        hexdump::hexdump(binary.as_slice());

        assert_eq!(binary.as_slice(), "/foo\0".as_bytes());

        let mut buf = binary.as_slice();
        let path = <&Path>::from_bytes(&mut buf).unwrap();
        assert_eq!(path.to_str().unwrap(), "/foo");
    }

    #[test]
    fn test_serde_absolute_path() {
        let path = Path::new("/foo");

        let json = serde_json::to_string(&path).unwrap();
        assert_eq!(json, "\"/foo\"");

        let path2: PathBuf = serde_json::from_str(&json).unwrap();
        assert_eq!(path2, path);

        let json2 = serde_json::to_string(&path2).unwrap();
        assert_eq!(json, json2);
    }
}