blob: 216837dc4c83bbbf9d8d7b00d18b50dc7aed2c5f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
package util
import (
"fmt"
"strings"
)
type BitfieldFormat uint8
const (
HexNone = BitfieldFormat(iota)
HexLower
HexUpper
)
func BitfieldString[T ~uint8 | ~uint16 | ~uint32 | ~uint64](bitfield T, bitnames []string, cfg BitfieldFormat) string {
var out strings.Builder
switch cfg {
case HexNone:
// do nothing
case HexLower:
fmt.Fprintf(&out, "0x%0x(", uint64(bitfield))
case HexUpper:
fmt.Fprintf(&out, "0x%0X(", uint64(bitfield))
}
if bitfield == 0 {
out.WriteString("none")
} else {
rest := bitfield
first := true
for i := 0; rest != 0; i++ {
if rest&(1<<i) != 0 {
if !first {
out.WriteRune('|')
}
if i < len(bitnames) {
out.WriteString(bitnames[i])
} else {
fmt.Fprintf(&out, "(1<<%d)", i)
}
first = false
}
rest &^= 1 << i
}
}
if cfg != HexNone {
out.WriteRune(')')
}
return out.String()
}
|