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 #[error(transparent)]
49 Other(#[from] anyhow::Error),
50}
51
52pub trait FromBytes<'a>: Sized {
54 fn from_bytes(buf: &mut &'a [u8]) -> Result<Self, FromBytesError>;
60
61 #[inline]
66 fn from_maybe_bytes(buf: Option<&mut &'a [u8]>) -> Result<Self, FromBytesError> {
67 match buf {
68 Some(buf) => Self::from_bytes(buf),
69 None => Err(FromBytesError::RequiredFieldNotFound),
70 }
71 }
72}
73
74impl<'a, T: FromBytes<'a> + 'a> FromBytes<'a> for Option<T>
75where
76 T: Sized,
77{
78 #[inline]
79 fn from_bytes(buf: &mut &'a [u8]) -> Result<Self, FromBytesError> {
80 T::from_bytes(buf).map(Some)
81 }
82
83 #[inline]
84 fn from_maybe_bytes(buf: Option<&mut &'a [u8]>) -> Result<Self, FromBytesError> {
85 match buf {
86 Some([]) => Ok(None),
87 Some(buf) => Self::from_bytes(buf),
88 None => Ok(None),
89 }
90 }
91}