tpm2_protocol/macro/
integer.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// Copyright (c) 2025 Opinsys Oy
3// Copyright (c) 2024-2025 Jarkko Sakkinen
4
5#[macro_export]
6macro_rules! tpm_integer {
7    ($ty:ty, $variant:ident) => {
8        impl TpmUnmarshal for $ty {
9            fn unmarshal(buf: &[u8]) -> TpmResult<(Self, &[u8])> {
10                let size = size_of::<$ty>();
11                let bytes = buf.get(..size).ok_or(TpmError::Truncated)?;
12                let array = bytes.try_into().map_err(|_| TpmError::Malformed)?;
13                let val = <$ty>::from_be_bytes(array);
14                Ok((val, &buf[size..]))
15            }
16        }
17
18        impl TpmMarshal for $ty {
19            fn marshal(&self, writer: &mut TpmWriter) -> TpmResult<()> {
20                writer.write_bytes(&self.to_be_bytes())
21            }
22        }
23
24        impl TpmSized for $ty {
25            const SIZE: usize = size_of::<$ty>();
26            fn len(&self) -> usize {
27                Self::SIZE
28            }
29        }
30
31        impl core::convert::From<$ty> for TpmDiscriminant {
32            fn from(value: $ty) -> Self {
33                Self::$variant(value.into())
34            }
35        }
36    };
37}