Debian Codegraph @

tpm2/bitfield.go

raw
1 package tpm2
2
3 import (
4 "fmt"
5 )
6
7 // Bitfield represents a TPM bitfield (i.e., TPMA_*) type.
8 type Bitfield interface {
9 // Length returns the length of the bitfield.
10 Length() int
11 }
12
13 // BitGetter represents a TPM bitfield (i.e., TPMA_*) type that can be read.
14 type BitGetter interface {
15 Bitfield
16 // GetReservedBit returns the value of the given reserved bit.
17 // If the bit is not reserved, returns false.
18 GetReservedBit(pos int) bool
19 }
20
21 // BitSetter represents a TPM bitfield (i.e., TPMA_*) type that can be written.
22 type BitSetter interface {
23 Bitfield
24 // GetReservedBit sets the value of the given reserved bit.
25 SetReservedBit(pos int, val bool)
26 }
27
28 func checkPos(pos int, len int) {
29 if pos >= len || pos < 0 {
30 panic(fmt.Errorf("bit %d out of range for %d-bit field", pos, len))
31 }
32 }
33
34 // bitfield8 represents an 8-bit bitfield which may have reserved bits.
35 // 8-bit TPMA_* types embed this one, and the reserved bits are stored in it.
36 type bitfield8 uint8
37
38 // Length implements the Bitfield interface.
39 func (bitfield8) Length() int {
40 return 8
41 }
42
43 // GetReservedBit implements the BitGetter interface.
44 func (r bitfield8) GetReservedBit(pos int) bool {
45 checkPos(pos, 8)
46 return r&(1<<pos) != 0
47 }
48
49 // SetReservedBit implements the BitSetter interface.
50 func (r *bitfield8) SetReservedBit(pos int, val bool) {
51 checkPos(pos, 8)
52 if val {
53 *r |= 1 << pos
54 } else {
55 *r &= ^(1 << pos)
56 }
57 }
58
59 // bitfield32 represents a 32-bit bitfield which may have reserved bits.
60 // 32-bit TPMA_* types embed this one, and the reserved bits are stored in it.
61 type bitfield32 uint32
62
63 // Length implements the Bitfield interface.
64 func (bitfield32) Length() int {
65 return 32
66 }
67
68 // GetReservedBit implements the BitGetter interface.
69 func (r bitfield32) GetReservedBit(pos int) bool {
70 checkPos(pos, 32)
71 return r&(1<<pos) != 0
72 }
73
74 // SetReservedBit implements the BitSetter interface.
75 func (r *bitfield32) SetReservedBit(pos int, val bool) {
76 checkPos(pos, 32)
77 if val {
78 *r |= 1 << pos
79 } else {
80 *r &= ^(1 << pos)
81 }
82 }