falco_event/fields/
from_bytes.rs1use thiserror::Error;
2
3#[derive(Error, Debug)]
5pub enum FromBytesError {
6 #[error("I/O error")]
8 IoError(#[from] std::io::Error),
9
10 #[error("required field not found")]
12 RequiredFieldNotFound,
13
14 #[error("internal NUL in string")]
16 InternalNul,
17
18 #[error("missing NUL terminator")]
20 MissingNul,
21
22 #[error("truncated field (wanted {wanted}, got {got})")]
24 TruncatedField {
25 wanted: usize,
27 got: usize,
29 },
30
31 #[error("invalid length")]
33 InvalidLength,
34
35 #[error("invalid PT_DYN discriminant")]
37 InvalidDynDiscriminant,
38
39 #[error("odd item count in pair array")]
41 OddPairItemCount,
42
43 #[error("trailing field data")]
45 LeftoverData,
46}
47
48pub trait FromBytes<'a>: Sized {
50 fn from_bytes(buf: &mut &'a [u8]) -> Result<Self, FromBytesError>;
56
57 fn from_maybe_bytes(buf: Option<&mut &'a [u8]>) -> Result<Self, FromBytesError> {
62 match buf {
63 Some(buf) => Self::from_bytes(buf),
64 None => Err(FromBytesError::RequiredFieldNotFound),
65 }
66 }
67}
68
69impl<'a, T: FromBytes<'a> + 'a> FromBytes<'a> for Option<T>
70where
71 T: Sized,
72{
73 fn from_bytes(buf: &mut &'a [u8]) -> Result<Self, FromBytesError> {
74 T::from_bytes(buf).map(Some)
75 }
76
77 fn from_maybe_bytes(buf: Option<&mut &'a [u8]>) -> Result<Self, FromBytesError> {
78 match buf {
79 Some([]) => Ok(None),
80 Some(buf) => Self::from_bytes(buf),
81 None => Ok(None),
82 }
83 }
84}