tpm2_protocol/basic/
list.rs1use crate::{TpmMarshal, TpmProtocolError, TpmResult, TpmSized, TpmUnmarshal};
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 push(&mut self, item: T) -> Result<(), TpmProtocolError> {
44 if self.len >= CAPACITY {
45 return Err(TpmProtocolError::TooManyItems);
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: TpmMarshal + Copy, const CAPACITY: usize> TpmMarshal for TpmList<T, CAPACITY> {
96 fn marshal(&self, writer: &mut crate::TpmWriter) -> TpmResult<()> {
97 let len = u32::try_from(self.len).map_err(|_| TpmProtocolError::OperationFailed)?;
98 TpmMarshal::marshal(&len, writer)?;
99 for item in &**self {
100 TpmMarshal::marshal(item, writer)?;
101 }
102 Ok(())
103 }
104}
105
106impl<T: TpmUnmarshal + Copy, const CAPACITY: usize> TpmUnmarshal for TpmList<T, CAPACITY> {
107 fn unmarshal(buf: &[u8]) -> TpmResult<(Self, &[u8])> {
108 let (count_u32, mut buf) = u32::unmarshal(buf)?;
109 let count = count_u32 as usize;
110 if count > CAPACITY {
111 return Err(TpmProtocolError::TooManyItems);
112 }
113
114 let mut list = Self::new();
115 for _ in 0..count {
116 let (item, rest) = T::unmarshal(buf)?;
117 list.push(item)?;
118 buf = rest;
119 }
120
121 Ok((list, buf))
122 }
123}