linux_audit_parser/
body.rs

1use std::fmt::{self, Debug};
2use std::ops::Range;
3
4#[cfg(feature = "serde")]
5use serde::{
6    de::{MapAccess, Visitor},
7    ser::SerializeMap,
8    Deserialize, Deserializer, Serialize, Serializer,
9};
10
11use crate::*;
12
13/// Parsed body of an Audit message, consisting of [`Key`]/[`Value`] pairs.
14pub struct Body<'a> {
15    elems: Vec<(Key, Value<'a>)>,
16    arena: Vec<Vec<u8>>,
17    _pin: std::marker::PhantomPinned,
18}
19
20impl<'a> PartialEq<Body<'a>> for Body<'a> {
21    fn eq(&self, other: &Self) -> bool {
22        self.elems == other.elems
23    }
24}
25
26impl Default for Body<'_> {
27    fn default() -> Self {
28        Body {
29            elems: Vec::with_capacity(8),
30            arena: vec![],
31            _pin: std::marker::PhantomPinned,
32        }
33    }
34}
35
36impl Debug for Body<'_> {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        let mut seq = f.debug_struct("Body");
39        for (k, v) in self {
40            seq.field(&k.to_string(), &v);
41        }
42        seq.finish()
43    }
44}
45
46#[cfg(feature = "serde")]
47impl Serialize for Body<'_> {
48    #[inline(always)]
49    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
50        let mut map = s.serialize_map(Some(self.elems.len()))?;
51        for (k, v) in self.into_iter() {
52            map.serialize_entry(&k, &v)?;
53        }
54        map.end()
55    }
56}
57
58#[derive(Default)]
59struct BodyVisitor<'a>(std::marker::PhantomData<Body<'a>>);
60
61impl<'a, 'de> Visitor<'de> for BodyVisitor<'a> {
62    type Value = Body<'a>;
63
64    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
65        formatter.write_str("a map")
66    }
67
68    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
69        let mut body = Body::new();
70        while let Some((k, v)) = map.next_entry::<Key, Value>()? {
71            body.push((k, v));
72        }
73        Ok(body)
74    }
75}
76
77impl<'de> Deserialize<'de> for Body<'_> {
78    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
79        d.deserialize_map(BodyVisitor::default())
80    }
81}
82
83impl Body<'_> {
84    /// Constructs a new, empty `Body`.
85    pub fn new() -> Self {
86        Self::default()
87    }
88
89    /// Constructs a new, empty `Body` with at least the specified
90    /// `capacity` for `Key`/`Value` entries.
91    pub fn with_capacity(len: usize) -> Self {
92        Self {
93            elems: Vec::with_capacity(len),
94            ..Self::default()
95        }
96    }
97
98    fn add_slice<'a, 'i>(&mut self, input: &'i [u8]) -> &'a [u8]
99    where
100        'a: 'i,
101    {
102        let ilen = input.len();
103
104        // let changed_buf: &Vec<u8>;
105        for buf in self.arena.iter() {
106            let Range { start, end } = input.as_ptr_range();
107            if buf.as_slice().as_ptr_range().contains(&start)
108                && buf.as_slice().as_ptr_range().contains(&end)
109            {
110                let s = std::ptr::slice_from_raw_parts(start, ilen);
111                return unsafe { &*s };
112            }
113        }
114        for buf in self.arena.iter_mut() {
115            if buf.capacity() - buf.len() > ilen {
116                let e = buf.len();
117                buf.extend(input);
118                let s = std::ptr::slice_from_raw_parts(buf[e..].as_ptr(), ilen);
119                return unsafe { &*s };
120            }
121        }
122        self.arena
123            .push(Vec::with_capacity(1014 * (1 + (ilen / 1024))));
124        let i = self.arena.len() - 1;
125        let new_buf = &mut self.arena[i];
126        new_buf.extend(input);
127        let s = std::ptr::slice_from_raw_parts(new_buf[..].as_ptr(), ilen);
128        unsafe { &*s }
129    }
130
131    fn add_value<'a, 'i>(&mut self, v: Value<'i>) -> Value<'a>
132    where
133        'a: 'i,
134    {
135        match v {
136            Value::Str(s, q) => Value::Str(self.add_slice(s), q),
137            Value::Owned(s) => Value::Str(self.add_slice(s.as_slice()), Quote::None),
138            Value::List(vs) => Value::List(vs.into_iter().map(|v| self.add_value(v)).collect()),
139            Value::StringifiedList(vs) => {
140                Value::StringifiedList(vs.into_iter().map(|v| self.add_value(v)).collect())
141            }
142            Value::Segments(vs) => {
143                let vs = vs.iter().map(|s| self.add_slice(s)).collect();
144                Value::Segments(vs)
145            }
146            Value::Map(vs) => Value::Map(
147                vs.into_iter()
148                    .map(|(k, v)| (k, self.add_value(v)))
149                    .collect(),
150            ),
151            // safety: These enum variants are self-contained.
152            Value::Empty | Value::Literal(_) | Value::Number(_) | Value::Skipped(_) => unsafe {
153                std::mem::transmute::<Value<'i>, Value<'a>>(v)
154            },
155        }
156    }
157
158    /// Appends `kv` to the back of a Body.
159    pub fn push(&mut self, kv: (Key, Value)) {
160        let (k, v) = kv;
161        let v = self.add_value(v);
162        self.elems.push((k, v));
163    }
164
165    /// Returns the number of elements in the `Body`.
166    pub fn len(&self) -> usize {
167        self.elems.len()
168    }
169
170    /// Extends Body with the elements of another `Body`.
171    pub fn extend(&mut self, other: Self) {
172        self.arena.extend(other.arena);
173        self.elems.reserve(other.elems.len());
174        for (k, v) in other.elems {
175            self.push((k, v));
176        }
177    }
178
179    /// Returns `true` if the `Body` has a length of 0.
180    pub fn is_empty(&self) -> bool {
181        self.elems.is_empty()
182    }
183
184    /// Retrieves the first value found for a given `key`.
185    pub fn get<K: AsRef<[u8]>>(&self, key: K) -> Option<&Value> {
186        let key = key.as_ref();
187        self.elems.iter().find(|(k, _)| k == key).map(|(_, v)| v)
188    }
189
190    /// Reserves capacity for at least `additional` more elements.
191    pub fn reserve(&mut self, additional: usize) {
192        self.elems.reserve(additional);
193    }
194}
195
196impl<'a> Body<'a> {
197    /// Retains only the elements specified by the predicate.
198    pub fn retain<F>(&mut self, f: F)
199    where
200        F: FnMut(&(Key, Value<'a>)) -> bool,
201    {
202        self.elems.retain(f)
203    }
204}
205
206impl Clone for Body<'_> {
207    fn clone(&self) -> Self {
208        let mut new = Body::default();
209        self.into_iter()
210            .cloned()
211            .for_each(|(k, v)| new.push((k, v)));
212        new
213    }
214}
215
216impl<'a> IntoIterator for &'a Body<'a> {
217    type Item = &'a (Key, Value<'a>);
218    type IntoIter = std::slice::Iter<'a, (Key, Value<'a>)>;
219    fn into_iter(self) -> Self::IntoIter {
220        self.elems.iter()
221    }
222}
223
224pub struct BodyIterator<'a> {
225    iter: std::vec::IntoIter<(Key, Value<'a>)>,
226    _arena: Vec<Vec<u8>>,
227    _pin: std::marker::PhantomPinned,
228}
229
230impl<'a> Iterator for BodyIterator<'a> {
231    type Item = (Key, Value<'a>);
232    fn next(&mut self) -> Option<Self::Item> {
233        self.iter.next()
234    }
235}
236
237impl<'a> IntoIterator for Body<'a> {
238    type Item = (Key, Value<'a>);
239    type IntoIter = BodyIterator<'a>;
240    fn into_iter(self) -> Self::IntoIter {
241        Self::IntoIter {
242            iter: self.elems.into_iter(),
243            _arena: self.arena,
244            _pin: std::marker::PhantomPinned,
245        }
246    }
247}