Debian Codegraph @

tpm2/tpm2b.go

raw
1 package tpm2
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "fmt"
7 "io"
8 )
9
10 // TPM2B is a helper type for all sized TPM structures. It can be instantiated with either a raw byte buffer or the actual struct.
11 type TPM2B[T Marshallable, P interface {
12 *T
13 Unmarshallable
14 }] struct {
15 contents *T
16 buffer []byte
17 }
18
19 // New2B creates a new TPM2B containing the given contents.
20 func New2B[T Marshallable, P interface {
21 *T
22 Unmarshallable
23 }](t T) TPM2B[T, P] {
24 return TPM2B[T, P]{contents: &t}
25 }
26
27 // BytesAs2B creates a new TPM2B containing the given byte array.
28 func BytesAs2B[T Marshallable, P interface {
29 *T
30 Unmarshallable
31 }](b []byte) TPM2B[T, P] {
32 return TPM2B[T, P]{buffer: b}
33 }
34
35 // Contents returns the structured contents of the TPM2B.
36 // It can fail if the TPM2B was instantiated with an invalid byte buffer.
37 func (value *TPM2B[T, P]) Contents() (*T, error) {
38 if value.contents != nil {
39 return value.contents, nil
40 }
41 if value.buffer == nil {
42 return nil, fmt.Errorf("TPMB had no contents or buffer")
43 }
44 contents, err := Unmarshal[T, P](value.buffer)
45 if err != nil {
46 return nil, err
47 }
48 // Cache the result
49 value.contents = (*T)(contents)
50 return value.contents, nil
51 }
52
53 // Bytes returns the inner contents of the TPM2B as a byte array, not including the length field.
54 func (value *TPM2B[T, P]) Bytes() []byte {
55 if value.buffer != nil {
56 return value.buffer
57 }
58 if value.contents == nil {
59 return []byte{}
60 }
61
62 // Cache the result
63 value.buffer = Marshal(*value.contents)
64 return value.buffer
65 }
66
67 // marshal implements the tpm2.Marshallable interface.
68 func (value TPM2B[T, P]) marshal(buf *bytes.Buffer) {
69 b := value.Bytes()
70 binary.Write(buf, binary.BigEndian, uint16(len(b)))
71 buf.Write(b)
72 }
73
74 // unmarshal implements the tpm2.Unmarshallable interface.
75 // Note: the structure contents are not validated during unmarshalling.
76 func (value *TPM2B[T, P]) unmarshal(buf *bytes.Buffer) error {
77 var size uint16
78 binary.Read(buf, binary.BigEndian, &size)
79 value.contents = nil
80 value.buffer = make([]byte, size)
81 _, err := io.ReadAtLeast(buf, value.buffer, int(size))
82 return err
83 }