tpm2_protocol/
list.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// Copyright (c) 2025 Opinsys Oy
3// Copyright (c) 2024-2025 Jarkko Sakkinen
4
5use crate::{TpmBuild, TpmErrorKind, TpmParse, TpmResult, TpmSized};
6use core::{
7    convert::TryFrom,
8    fmt::Debug,
9    mem::{size_of, MaybeUninit},
10    ops::Deref,
11    slice,
12};
13
14/// A fixed-capacity list for TPM structures, implemented over a fixed-size array.
15#[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    /// Creates a new, empty `TpmList`.
23    #[must_use]
24    pub fn new() -> Self {
25        Self {
26            items: [const { MaybeUninit::uninit() }; CAPACITY],
27            len: 0,
28        }
29    }
30
31    /// Returns `true` if the list contains no elements.
32    #[must_use]
33    pub fn is_empty(&self) -> bool {
34        self.len == 0
35    }
36
37    /// Appends an element to the back of the list.
38    ///
39    /// # Errors
40    ///
41    /// Returns a `TpmErrorKind::Capacity` error if the list is already at
42    /// full capacity.
43    pub fn try_push(&mut self, item: T) -> Result<(), TpmErrorKind> {
44        if self.len >= CAPACITY {
45            return Err(TpmErrorKind::Capacity(CAPACITY));
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    /// # Safety
58    ///
59    /// This implementation uses `unsafe` to provide a view into the initialized
60    /// portion of the list. The caller can rely on this being safe because:
61    /// 1. The first `self.len` items are guaranteed to be initialized by the `try_push` method.
62    /// 2. `MaybeUninit<T>` is guaranteed to have the same memory layout as `T`.
63    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)
98            .map_err(|_| TpmErrorKind::Capacity(usize::try_from(u32::MAX).unwrap_or(usize::MAX)))?;
99        TpmBuild::build(&len, writer)?;
100        for item in &**self {
101            TpmBuild::build(item, writer)?;
102        }
103        Ok(())
104    }
105}
106
107impl<T: TpmParse + Copy, const CAPACITY: usize> TpmParse for TpmList<T, CAPACITY> {
108    fn parse(buf: &[u8]) -> TpmResult<(Self, &[u8])> {
109        let (count_u32, mut buf) = u32::parse(buf)?;
110        let count = count_u32 as usize;
111        if count > CAPACITY {
112            return Err(TpmErrorKind::Capacity(CAPACITY));
113        }
114
115        let mut list = Self::new();
116        for _ in 0..count {
117            let (item, rest) = T::parse(buf)?;
118            list.try_push(item).map_err(|_| TpmErrorKind::Failure)?;
119            buf = rest;
120        }
121
122        Ok((list, buf))
123    }
124}