falco_event/fields/
to_bytes.rs

1use std::io::Write;
2
3/// Convert a field to binary representation
4pub trait ToBytes {
5    /// Return the number of bytes needed to store the field
6    fn binary_size(&self) -> usize;
7
8    /// Write the binary representation to `writer`
9    fn write<W: Write>(&self, writer: W) -> std::io::Result<()>;
10
11    /// Return the default representation for the field type
12    ///
13    /// **Note**: this does not need to be the same type as the implementing type.
14    /// For example, an empty C-style string can be represented e.g. by returning `0u8`.
15    fn default_repr() -> impl ToBytes;
16}
17
18/// A pseudo-field that cannot be written (returns an error at runtime)
19///
20/// This is useful for types that do not have a default representation (e.g. `PT_DYN` types)
21///
22/// **Note**: all event fields are generated as `Option<T>`, so there is always a possibility
23/// that we get to write a default value for a field that does not have one.
24pub struct NoDefault;
25
26impl ToBytes for NoDefault {
27    #[inline]
28    fn binary_size(&self) -> usize {
29        0
30    }
31
32    #[inline]
33    fn write<W: Write>(&self, _writer: W) -> std::io::Result<()> {
34        Err(std::io::Error::new(
35            std::io::ErrorKind::InvalidData,
36            "field cannot be empty when writing",
37        ))
38    }
39
40    #[inline]
41    fn default_repr() -> impl ToBytes {
42        Self
43    }
44}
45
46impl<T: ToBytes> ToBytes for Option<T> {
47    #[inline]
48    fn binary_size(&self) -> usize {
49        if let Some(inner) = &self {
50            inner.binary_size()
51        } else {
52            Self::default_repr().binary_size()
53        }
54    }
55
56    #[inline]
57    fn write<W: Write>(&self, writer: W) -> std::io::Result<()> {
58        match self {
59            Some(val) => val.write(writer),
60            None => T::default_repr().write(writer),
61        }
62    }
63
64    #[inline]
65    fn default_repr() -> impl ToBytes {
66        T::default_repr()
67    }
68}