1use super::arrays::SimpleArrayView;
6use super::parser::{PolicyCursor, PolicyData, PolicyOffset};
7use super::{Counted, Parse, PolicyValidationContext, Validate};
8
9use hashbrown::hash_table::HashTable;
10use rapidhash::RapidHasher;
11use static_assertions::const_assert;
12use std::fmt::Debug;
13use std::hash::{Hash, Hasher};
14use std::marker::PhantomData;
15use zerocopy::{FromBytes, Immutable, KnownLayout, Unaligned};
16
17pub trait HasMetadata {
23 type Metadata: FromBytes + Sized;
25}
26
27pub trait Walk {
31 fn walk(policy_data: &PolicyData, offset: PolicyOffset) -> PolicyOffset;
35}
36
37#[derive(Debug, Clone, Copy)]
42pub struct View<T> {
43 phantom: PhantomData<T>,
44
45 start: PolicyOffset,
47
48 end: PolicyOffset,
50}
51
52impl<T> View<T> {
53 pub fn new(start: PolicyOffset, end: PolicyOffset) -> Self {
55 Self { phantom: PhantomData, start, end }
56 }
57
58 fn start(&self) -> PolicyOffset {
60 self.start
61 }
62}
63
64impl<T: Sized> View<T> {
65 pub fn at(start: PolicyOffset) -> Self {
69 let end = start + std::mem::size_of::<T>() as u32;
70 Self::new(start, end)
71 }
72}
73
74impl<T: FromBytes + Sized> View<T> {
75 pub fn read(&self, policy_data: &PolicyData) -> T {
82 debug_assert_eq!(self.end - self.start, std::mem::size_of::<T>() as u32);
83 let start = self.start as usize;
84 let end = self.end as usize;
85 T::read_from_bytes(&policy_data[start..end]).unwrap()
86 }
87}
88
89impl<T: HasMetadata> View<T> {
90 pub fn metadata(&self) -> View<T::Metadata> {
94 View::<T::Metadata>::at(self.start)
95 }
96
97 pub fn read_metadata(&self, policy_data: &PolicyData) -> T::Metadata {
99 self.metadata().read(policy_data)
100 }
101}
102
103impl<T: Parse> View<T> {
104 pub fn parse(&self, policy_data: &PolicyData) -> T {
110 let cursor = PolicyCursor::new_at(policy_data, self.start);
111 let (object, _) =
112 T::parse(cursor).map_err(Into::<anyhow::Error>::into).expect("policy should be valid");
113 object
114 }
115}
116
117impl<T: Validate + Parse> Validate for View<T> {
118 type Error = anyhow::Error;
119
120 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
121 let object = self.parse(&context.data);
122 object.validate(context).map_err(Into::<anyhow::Error>::into)
123 }
124}
125
126#[derive(Debug, Clone, Copy)]
131pub struct ArrayDataView<D> {
132 phantom: PhantomData<D>,
133 start: PolicyOffset,
134 count: u32,
135}
136
137impl<D> ArrayDataView<D> {
138 pub fn new(start: PolicyOffset, count: u32) -> Self {
140 Self { phantom: PhantomData, start, count }
141 }
142
143 pub fn iter(self, policy_data: &PolicyData) -> ArrayDataViewIter<D> {
150 ArrayDataViewIter::new(policy_data.clone(), self.start, self.count)
151 }
152}
153
154pub struct ArrayDataViewIter<D> {
159 phantom: PhantomData<D>,
160 policy_data: PolicyData,
161 offset: PolicyOffset,
162 remaining: u32,
163}
164
165impl<T> ArrayDataViewIter<T> {
166 fn new(policy_data: PolicyData, offset: PolicyOffset, remaining: u32) -> Self {
168 Self { phantom: PhantomData, policy_data, offset, remaining }
169 }
170}
171
172impl<D: Walk> std::iter::Iterator for ArrayDataViewIter<D> {
173 type Item = View<D>;
174
175 fn next(&mut self) -> Option<Self::Item> {
176 if self.remaining > 0 {
177 let start = self.offset;
178 self.offset = D::walk(&self.policy_data, start);
179 self.remaining -= 1;
180 Some(View::new(start, self.offset))
181 } else {
182 None
183 }
184 }
185}
186
187#[derive(Debug, Clone, Copy)]
192pub(super) struct ArrayView<M, D> {
193 phantom: PhantomData<(M, D)>,
194 start: PolicyOffset,
195 count: u32,
196}
197
198impl<M, D> ArrayView<M, D> {
199 pub fn new(start: PolicyOffset, count: u32) -> Self {
201 Self { phantom: PhantomData, start, count }
202 }
203}
204
205impl<M: Sized, D> ArrayView<M, D> {
206 pub fn metadata(&self) -> View<M> {
208 View::<M>::at(self.start)
209 }
210
211 pub fn data(&self) -> ArrayDataView<D> {
213 ArrayDataView::new(self.metadata().end, self.count)
214 }
215}
216
217fn parse_array_data<'a, D: Parse>(
218 cursor: PolicyCursor<'a>,
219 count: u32,
220) -> Result<PolicyCursor<'a>, anyhow::Error> {
221 let mut tail = cursor;
222 for _ in 0..count {
223 let (_, next) = D::parse(tail).map_err(Into::<anyhow::Error>::into)?;
224 tail = next;
225 }
226 Ok(tail)
227}
228
229impl<M: Counted + Parse + Sized, D: Parse> Parse for ArrayView<M, D> {
230 type Error = anyhow::Error;
233
234 fn parse<'a>(cursor: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error> {
235 let start = cursor.offset();
236 let (metadata, cursor) = M::parse(cursor).map_err(Into::<anyhow::Error>::into)?;
237 let count = metadata.count();
238 let cursor = parse_array_data::<D>(cursor, count)?;
239 Ok((Self::new(start, count), cursor))
240 }
241}
242
243struct HashedArrayViewEntryIter<'a, D: HasMetadata> {
246 policy_data: &'a PolicyData,
247 limit: PolicyOffset,
248 metadata: D::Metadata,
249 offset: Option<PolicyOffset>,
250}
251
252#[derive(Clone, Copy, Debug, KnownLayout, FromBytes, Immutable, PartialEq, Unaligned)]
259#[repr(C, packed)]
260pub(super) struct U24 {
261 low: u8,
262 middle: u8,
263 high: u8,
264}
265
266const_assert!(std::mem::size_of::<U24>() == 3);
268const_assert!(std::mem::align_of::<U24>() == 1);
269
270impl TryFrom<u32> for U24 {
271 type Error = ();
272
273 fn try_from(value: u32) -> Result<Self, Self::Error> {
274 if 0x1000000 <= value {
275 Err(())
276 } else {
277 Ok(Self {
278 low: (value & 0xff) as u8,
279 middle: ((value >> 8) & 0xff) as u8,
280 high: ((value >> 16) & 0xff) as u8,
281 })
282 }
283 }
284}
285
286impl From<U24> for u32 {
287 fn from(value: U24) -> u32 {
288 ((value.high as u32) << 16) + ((value.middle as u32) << 8) + (value.low as u32)
289 }
290}
291
292impl<'a, D: HasMetadata + Walk> Iterator for HashedArrayViewEntryIter<'a, D>
293where
294 D::Metadata: Eq,
295{
296 type Item = View<D>;
297
298 fn next(&mut self) -> Option<Self::Item> {
299 if let Some(offset) = self.offset
300 && offset < self.limit
301 {
302 let element = View::<D>::at(offset);
303 let metadata = element.read_metadata(&self.policy_data);
304 if metadata == self.metadata {
305 self.offset = Some(D::walk(&self.policy_data, offset));
306 Some(element)
307 } else {
308 self.offset = None;
309 None
310 }
311 } else {
312 None
313 }
314 }
315}
316
317#[derive(Debug, Clone)]
322pub(super) struct HashedArrayView<D: HasMetadata> {
323 phantom: PhantomData<D>,
324 index: HashTable<U24>,
325 limit: PolicyOffset,
329}
330
331impl<D: HasMetadata> HashedArrayView<D>
332where
333 D::Metadata: Hash,
334{
335 fn metadata_hash(metadata: &D::Metadata) -> u64 {
336 let mut hasher = RapidHasher::default();
337 metadata.hash(&mut hasher);
338 hasher.finish()
339 }
340}
341
342impl<D: Parse + HasMetadata + Walk> HashedArrayView<D>
343where
344 D::Metadata: Eq + PartialEq + Hash + Debug,
345{
346 pub fn find(&self, key: D::Metadata, policy_data: &PolicyData) -> Option<D> {
351 let key_hash = Self::metadata_hash(&key);
352 let offset = self.index.find(key_hash, |&offset| {
353 let element = View::<D>::at(u32::from(offset));
354 key == element.read_metadata(policy_data)
355 })?;
356 let element = View::<D>::at(u32::from(*offset));
357 Some(element.parse(policy_data))
358 }
359
360 pub(super) fn find_all(
363 &self,
364 key: D::Metadata,
365 policy_data: &PolicyData,
366 ) -> impl Iterator<Item = D> {
367 let key_hash = Self::metadata_hash(&key);
368 let offset = self.index.find(key_hash, |&offset| {
369 let element = View::<D>::at(u32::from(offset));
370 key == element.read_metadata(policy_data)
371 });
372 (HashedArrayViewEntryIter {
373 policy_data: policy_data,
374 limit: self.limit,
375 metadata: key,
376 offset: offset.map(|offset| u32::from(*offset)),
377 })
378 .map(|element| element.parse(policy_data))
379 }
380
381 pub(super) fn iter(&self, policy_data: &PolicyData) -> impl Iterator<Item = View<D>> {
383 self.index
384 .iter()
385 .map(|offset| {
386 let element = View::<D>::at(u32::from(*offset));
387 HashedArrayViewEntryIter {
388 policy_data: policy_data,
389 limit: self.limit,
390 metadata: element.read_metadata(policy_data),
391 offset: Some(u32::from(*offset)),
392 }
393 })
394 .flatten()
395 }
396}
397
398impl<D: Parse + HasMetadata + Walk> Parse for HashedArrayView<D>
399where
400 D::Metadata: Eq + Debug + PartialEq + Parse + Hash,
401{
402 type Error = anyhow::Error;
403
404 fn parse<'a>(cursor: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error> {
405 let (array_view, cursor) = SimpleArrayView::<D>::parse(cursor)?;
406
407 let mut index = HashTable::with_capacity(array_view.count as usize);
409
410 let limit = cursor.offset();
412
413 for view in array_view.data().iter(cursor.data()) {
416 let metadata = view.read_metadata(cursor.data());
417
418 index
419 .entry(
420 Self::metadata_hash(&metadata),
421 |&offset| {
422 let element = View::<D>::at(u32::from(offset));
423 metadata == element.read_metadata(cursor.data())
424 },
425 |&offset| {
426 let element = View::<D>::at(u32::from(offset));
427 Self::metadata_hash(&element.read_metadata(cursor.data()))
428 },
429 )
430 .or_insert(U24::try_from(view.start()).expect("Policy offsets ought fit in U24!"));
431 }
432
433 Ok((Self { phantom: PhantomData, index, limit }, cursor))
434 }
435}
436
437impl<D: Validate + Parse + HasMetadata + Walk> Validate for HashedArrayView<D>
438where
439 D::Metadata: Eq,
440{
441 type Error = anyhow::Error;
442
443 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
444 let policy_data = context.data.clone();
445 for element in self
446 .index
447 .iter()
448 .map(|offset| {
449 let element = View::<D>::at(u32::from(*offset));
450 HashedArrayViewEntryIter::<D> {
451 policy_data: &policy_data,
452 limit: self.limit,
453 metadata: element.read_metadata(&policy_data),
454 offset: Some(u32::from(*offset)),
455 }
456 })
457 .flatten()
458 {
459 element.validate(context)?;
460 }
461
462 Ok(())
463 }
464}
465
466#[cfg(test)]
467mod tests {
468 use super::U24;
469
470 #[test]
471 fn to_and_from_u24() {
472 for i in 0u32..0x10000 {
473 let u24_result = U24::try_from(i);
474 assert!(u24_result.is_ok());
475 let u24 = u24_result.unwrap();
476 assert_eq!(i >> 16, u24.high as u32);
477 assert_eq!((i >> 8) & 0xff, u24.middle as u32);
478 assert_eq!(i & 0xff, u24.low as u32);
479 let j = u32::from(u24);
480 assert_eq!(i, j);
481 }
482
483 assert!(U24::try_from(0x1000000).is_err());
484 }
485}