Debian Codegraph @

src/body.rs

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