tpm2_protocol/basic/
list.rs1use crate::{TpmBuild, TpmError, TpmParse, TpmResult, TpmSized};
6use core::{
7 convert::TryFrom,
8 fmt::Debug,
9 mem::{size_of, MaybeUninit},
10 ops::Deref,
11 slice,
12};
13
14#[derive(Clone, Copy)]
16pub struct TpmList<T: Copy, const CAPACITY: usize> {
17 items: [MaybeUninit<T>; CAPACITY],
18 len: usize,
19}
20
21impl<T: Copy, const CAPACITY: usize> TpmList<T, CAPACITY> {
22 #[must_use]
24 pub fn new() -> Self {
25 Self {
26 items: [const { MaybeUninit::uninit() }; CAPACITY],
27 len: 0,
28 }
29 }
30
31 #[must_use]
33 pub fn is_empty(&self) -> bool {
34 self.len == 0
35 }
36
37 pub fn try_push(&mut self, item: T) -> Result<(), TpmError> {
44 if self.len >= CAPACITY {
45 return Err(TpmError::CapacityExceeded);
46 }
47 self.items[self.len].write(item);
48 self.len += 1;
49 Ok(())
50 }
51}
52
53#[allow(unsafe_code)]
54impl<T: Copy, const CAPACITY: usize> Deref for TpmList<T, CAPACITY> {
55 type Target = [T];
56
57 fn deref(&self) -> &Self::Target {
64 unsafe { slice::from_raw_parts(self.items.as_ptr().cast::<T>(), self.len) }
65 }
66}
67
68impl<T: Copy, const CAPACITY: usize> Default for TpmList<T, CAPACITY> {
69 fn default() -> Self {
70 Self::new()
71 }
72}
73
74impl<T: Copy + Debug, const CAPACITY: usize> Debug for TpmList<T, CAPACITY> {
75 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76 f.debug_list().entries(self.iter()).finish()
77 }
78}
79
80impl<T: Copy + PartialEq, const CAPACITY: usize> PartialEq for TpmList<T, CAPACITY> {
81 fn eq(&self, other: &Self) -> bool {
82 **self == **other
83 }
84}
85
86impl<T: Copy + Eq, const CAPACITY: usize> Eq for TpmList<T, CAPACITY> {}
87
88impl<T: TpmSized + Copy, const CAPACITY: usize> TpmSized for TpmList<T, CAPACITY> {
89 const SIZE: usize = size_of::<u32>() + (T::SIZE * CAPACITY);
90 fn len(&self) -> usize {
91 size_of::<u32>() + self.iter().map(TpmSized::len).sum::<usize>()
92 }
93}
94
95impl<T: TpmBuild + Copy, const CAPACITY: usize> TpmBuild for TpmList<T, CAPACITY> {
96 fn build(&self, writer: &mut crate::TpmWriter) -> TpmResult<()> {
97 let len = u32::try_from(self.len).map_err(|_| TpmError::CapacityExceeded)?;
98 TpmBuild::build(&len, writer)?;
99 for item in &**self {
100 TpmBuild::build(item, writer)?;
101 }
102 Ok(())
103 }
104}
105
106impl<T: TpmParse + Copy, const CAPACITY: usize> TpmParse for TpmList<T, CAPACITY> {
107 fn parse(buf: &[u8]) -> TpmResult<(Self, &[u8])> {
108 let (count_u32, mut buf) = u32::parse(buf)?;
109 let count = count_u32 as usize;
110 if count > CAPACITY {
111 return Err(TpmError::CapacityExceeded);
112 }
113
114 let mut list = Self::new();
115 for _ in 0..count {
116 let (item, rest) = T::parse(buf)?;
117 list.try_push(item)?;
118 buf = rest;
119 }
120
121 Ok((list, buf))
122 }
123}