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 TpmParse for $ty {
9            fn parse(buf: &[u8]) -> TpmResult<(Self, &[u8])> {
10                let size = size_of::<$ty>();
11                if buf.len() < size {
12                    return Err(TpmErrorKind::Underflow);
13                }
14                let (bytes, buf) = buf.split_at(size);
15                let mut array = [0u8; size_of::<$ty>()];
16                array.copy_from_slice(bytes);
17                let val = <$ty>::from_be_bytes(array);
18                Ok((val, buf))
19            }
20        }
21
22        impl TpmBuild for $ty {
23            fn build(&self, writer: &mut TpmWriter) -> TpmResult<()> {
24                writer.write_bytes(&self.to_be_bytes())
25            }
26        }
27
28        impl TpmSized for $ty {
29            const SIZE: usize = size_of::<$ty>();
30            fn len(&self) -> usize {
31                Self::SIZE
32            }
33        }
34
35        impl core::convert::From<$ty> for TpmNotDiscriminant {
36            fn from(value: $ty) -> Self {
37                Self::$variant(value.into())
38            }
39        }
40    };
41}